jeudi 30 juillet 2020

(jquery) Defining website position in relate to elements on the page using window.pageYOffset. "If" statements does not work, why and how to fix it?

I'm trying to define position of window in relate to div's in my page so I'll be able to add & remove classes from menu items during scroll when window will enter certain position.

But first I have a simple question, well maybe more than one simple question ;). Why when I write if( /* smth */ > var1 + var2) adding two variables this way does not apply? Why does statement var fromTop = window.pageYOffset + var1; does not work, while var1 is outerHeight() of element?

Now to the the topic of question:

My jquery code looks like this:

   <script type="text/javascript">
        $(document).ready(function() {
           var headerheight = $("#main_header_div").outerHeight();
           var mainpageheight = $("#Strona_glowna").outerHeight();
           var offerheight = $("#Oferta").outerHeight();
           var aboutheight = $("#O_nas").outerHeight();
          
          
            $(window).scroll(function () {
            var fromTop = window.pageYOffset + 90;
             
              
              if(fromTop < mainpageheight ){
              alert("mainpage");
              } else if((fromTop > mainpageheight)&&(fromTop =< mainpageheight + offerheight)) {
              alert("offer");
              } else if((fromTop > mainpageheight + offerheight)&&(fromTop =< mainpageheight + 
              offerheight + aboutheight)) {
              alert("about");
              }
             
            });
        });
      
      
      
      </script>

I added these alerts becouse I didin't want to mess with adding/removing classes and css until this basic scrypt works.

So as you see the script should cause a popup alert when the window is in certain position but it doesn't, why and how to fix it?

Aucun commentaire:

Enregistrer un commentaire