Rotate on scroll javascript not working when getElementsByClassName

Viewed 71

I'm using the following js code to rotate various elements on scroll. It works perfectly fine as long as I getElementById. However, there is one image that I would like to rotate that does not have id. Instead, it has several classes. Naturally, I replace getElementById with getElementsByClassName. The problem is that whenever I do that, the code does not work.

Here is the working code:

<img src="url" id="logo">

<script>
var example = document.getElementById("logo");
window.addEventListener("scroll", function() {
    example.style.transform = "rotate("+window.pageYOffset/10+"deg)";
});
</script>

Here is the non-working code:

<img src="url" class="circle">

<script>
var example = document.getElementsByClassName("circle");
window.addEventListener("scroll", function() {
    example.style.transform = "rotate("+window.pageYOffset/10+"deg)";
});
</script>

P.S. I do not have access to HTML.

2 Answers

The issue is on that line:

var example = document.getElementsByClassName("circle");

The function named getElementsByClassName return an array, can be a element but in array, not like does for example getElementById passes directly the element, in that case, i assume, the circle class is the first element you want to get, do the next:

var example = document.getElementsByClassName("circle")[0];

More info of that function:

https://developer.mozilla.org/es/docs/Web/API/Document/getElementsByClassName

Related