1

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?

Garb o' Donk
  • 53
  • 1
  • 3
  • Well, apparently `balls[0]` (or `balls[1]`) is undefined. I don't have context to see what `document.getElementsByClassName("text1");` is, but it is not returning an array as you seem to expect. – C. Peck May 14 '21 at 10:30

1 Answers1

1

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>
Luis
  • 2,665
  • 8
  • 44
  • 70
Shubham
  • 206
  • 1
  • 9