Creating a JS animation with SVG using HTML and CSS

Asked

Viewed 68 times

-1

I’m starting studies with SVG and trying to understand an example I can not run it correctly, the HTML/CSS/JS parts were demonstrated and I made the connection of these parts, but it didn’t work... If anyone can tell me what I’m doing wrong it would be very helpful:

<html>

  <head>
    <title>Exemplo Teste</title>
    <style>
      .meu-circulo {
        r: 30;
        cx: 50;
        cy: 40;
        fill: lightgreen;
        stroke: orange;
        stroke-width: 5;
        transition: all 1s ease;
      }

      .meu-circulo:hover {
        cx: 70;
        fill: green;
        stroke-width: 10;
      }

    </style>
    <script>
      const circle = document.querySelector('.meu-circulo');
      let r = 30;

      circle.addEventListener('click', () => {
        r += 10;
        circle.style.r = r;
      })

    </script>
  </head>

  <body>
    <svg>
      <circle class="meu-circulo"></circle>
    </svg>
  </body>

</html>
  • But what didn’t work??

  • Do not draw the circle and apply the JS effect of increasing the radius with the click event

1 answer

1

The problem is because when the line is called:

const circle = document.querySelector('.meu-circulo');

The element:

<circle class="meu-circulo"></circle>

Does not yet exist generating the error:

cannot read Property of Undefined

On the line:

circle.addEventListener('click', () => {

To solve the problem put the script inside the event 'load' document or its script will only be triggered after the page loads.

<html>

<head>
  <title>Exemplo Teste</title>
  <style>
    .meu-circulo {
      r: 30;
      cx: 50;
      cy: 40;
      fill: lightgreen;
      stroke: orange;
      stroke-width: 5;
      transition: all 1s ease;
    }
    
    .meu-circulo:hover {
      cx: 70;
      fill: green;
      stroke-width: 10;
    }
  </style>
  <script>
    window.addEventListener("load", function(event) {


      const circle = document.querySelector('.meu-circulo');
      let r = 30;

      circle.addEventListener('click', () => {
        r += 10;
        circle.style.r = r;
      })
    });
  </script>
</head>

<body>
  <svg>
      <circle class="meu-circulo"></circle>
    </svg>
</body>

</html>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.