r4tchet r4tchet - 17 days ago 6
CSS Question

JavaScript to change appearance of elements on scroll

Okay, so I had this JavaScript and it was working perfectly fine.



var header = document.getElementById('header');

window.onscroll = function () {
"use strict";
if (document.body.scrollTop >= 6) {
header.className = 'header-colored';
} else {
header.className = 'header-transparent';
}
};





But when I added another element to the script, it stopped working for some reason. Stopped working as in header stays transparent and arrow is always visible.

All relevant code (i believe):



var header = document.getElementById('header');
var arrow = document.getElementsById('arrowToTop');
window.onscroll = function () {
"use strict";
if (document.body.scrollTop >= 6) {
header.className = 'header-colored';
arrow.className = 'arrow-visible';
} else {
header.className = 'header-transparent';
arrow.className = 'arrow-transparent';
}
};

#header {
position: fixed;
}

.header-transparent {
background-color: transparent;
}

.header-colored {
background-color: black;
opacity: .9;
}

.toTop {
bottom: 0;
right: 0;
position: fixed;
}

.arrow-visible {
display: block;
}

.arrow-transparent {
display: none;
}

<header id="header" class="header-transparent">
<img src="Bilder/LOGO.png" alt="Blabla" style="width: 10%;">
<ul id="navbar">
<li><a href="#allText">home</a></li>
<li><a href="#">business</a></li>
<li><a href="#">technical</a></li>
<li><a href="#">about us</a></li>
</ul>
</header>

</div>
<i class="material-icons" id="arrowToTop"><a class="toTop" href="#">keyboard_arrow_up</a></i>
</div>





Does anyone know the reason why the script stopped working when I added a new variable and two extra lines of code?
Thanks!

Answer

Your declaration of arrow is plural. Change this

  var arrow = document.getElementsById('arrowToTop');

To

 var arrow = document.getElementById('arrowToTop');

I don't see how you didn't get an error for that. It's not a JS function.