Heyo,
is there any way I can get this script:
function parallax (){
var paralax_effect = document.getElementById('div1');
paralax_effect.style.top = -(window.pageYOffset / 4)+'px';
}
window.addEventListener('scroll', parallax, false);
to run multiple Classes
instead of one Id
?
I tried this:
function parallax (){
var paralax_effect = document.getElementsByClassName('div1');
paralax_effect.style.top = -(window.pageYOffset / 4)+'px';
}
window.addEventListener('scroll', parallax, false);
but this somehow doesn't work.
Thanks in advance!
getElementsByClassName
returns not a single element but a whole list of elements, whereas getElementById
(notice the difference in the word Element/Elements) returns only a single element.
So in your second code, you store a list of elements with the class "div1" in var paralax_effect
. In order to manipulate those elements you have to loop over them with for
. Example:
for (var i = 0; i < paralax_effect.length; i++) {
current_element = paralax_effect[i]
current_element.style.top = -(window.pageYOffset / 4)+'px';
}
This requires your HTML to have at least one element with class="div1"
.