Search code examples
javascripthtmlcssstylesscrollbar

CSS (scrolling): why is it not possible to base the command on class name instead of id?


I wanted to make a topbar reacting to scrolling on the website.

I have used this command:

window.onscroll = function() {scrollFunction()};

function scrollFunction() {
  if (document.body.scrollTop > 200 || document.documentElement.scrollTop > 200) {
//    SMALL!!
    document.getElementById("logo_nav_bar").style.height = " 100px";    
}  
//  BIG!!
   else {
    document.getElementById("logo_nav_bar").style.height = "160px";
}

Question: do I have to always use getElementById? because getElementsByClassName did not work and I would like to apply this command to the whole class.


Solution

  • Assuming we are not using jQuery, You can try following: Replace className with your class, and change required attribute, I changed color for a sample.

    function scrollFunction() {
       if (document.body.scrollTop > 200 || document.documentElement.scrollTop > 200) {
          //    SMALL!!
          var elements = document.getElementsByClassName("className");
          for(let i=0; i<elements.length; i++) {
              elements[i].style.color = "yellow";
          }
       }  
    //  BIG!!
       else {
        var elements = document.getElementsByClassName("className");
        for(let i=0; i<elements.length; i++) {
            elements[i].style.color = "red";
        }
    }