Search code examples
javascripthtmlcursorundefinedonmousemove

"Cannot read property 'style' of undefined" onmousemove


So on my website, I want some text to follow my cursor. I use the following JS:

var balls = document.getElementsByClassName("text1");
  document.onmousemove = function(){
    var x = event.clientX * 100 / window.innerWidth + "%";
    var y = event.clientY * 100 / window.innerHeight + "%";

    for(var i=0;i<2;i++){
      balls[i].style.left = x;
      balls[i].style.top = y;
      balls[i].style.transform = "translate(-"+x+",-"+y+")";
    }
  };

but in chrome I get the following error message:

Uncaught TypeError: Cannot read property 'style' of undefined at HTMLDocument.document.onmousemove (script.js:7) document.onmousemove @ script.js:7

Can anyone help me?


Solution

  • The problem in your code is that you are looping till "i==2" but you might have attached the "text1" class to only 1 element and that's why when the loop reached balls[1] then it threw the error of "Cannot read property 'style' of undefined".

    So either decreases the loop maximum value or attaching the "text1" class to more elements.

    Here is the working example.

    <!DOCTYPE html>
    <html>
    <script>
      var balls = document.getElementsByClassName("text1");
      document.onmousemove = function() {
        var x = event.clientX * 100 / window.innerWidth + "%";
        var y = event.clientY * 100 / window.innerHeight + "%";
        for (var i = 0; i < 2; i++) {
          balls[i].style.left = x;
          balls[i].style.top = y;
          balls[i].style.transform = "translate(-" + x + ",-" + y + ")";
        }
      };
    </script>
    
    <body>
      <p class="text1">Hello</p>
      <p class="text1">World</p>
    </body>
    
    </html>