0

My mobile nav for a website Im making with HTML CSS and BS3, is very basic. but im wanting to disable scrolling of the rest of the body when I toggle the hamburger button.

My issue is that when its turned on, you cant scroll, which is what i want. But when you toggle off the menu, it doesnt work.

heres some of the HTML:

  <!--        mobile nav links-->
              <div class="mob-div-nav">
                <div class="row">
                  <div class="col-xs-12" style="height:100%;">

                  </div>
                </div>
              </div>
      <!--        END Mobile Nav-->

Here is the Js:

  $("#hamburger").on("click", function (event){

  $(".mob-div-nav").slideToggle(500);

  function noscroll() {
  window.scrollTo( 0, 0 );
}
  // add listener to disable scroll

  if ($(".mob-div-nav").css("display") == "block"){

    window.addEventListener('scroll', noscroll);

    } else if ($(".mob-div-nav").css("display") == "none") {

      window.removeEventListener('scroll', noscroll);

    }
});

1 Answers1

0

use the if statement inside the function not outside .. your code should looks like this

$(document).ready(function(){
  // #hamburger click event
  $("#hamburger").on("click", function (event){
    $(".mob-div-nav").slideToggle(500);
  }); // End of #hamburger click event
  // window scroll event
  $(window).on('scroll' , noscroll);
});

// functions here
// noscroll function
function noscroll() {
  if ($(".mob-div-nav").is(':visible')){
    window.scrollTo( 0, 0 );
  }
}

Explanation:

  • $(document).ready(function(){ - when document is ready read Here
  • window.addEventListener is a pure javascript and $(window).on('scroll' is a jquery .. jQuery .on(); vs JavaScript .addEventListener();
  • .is(':visible') is a jquery function check if the element is visible , :hidden if the element is hidden , :checked if checked and so on .. you can read about .is() here
Mohamed-Yousef
  • 23,946
  • 3
  • 19
  • 28
  • So im new to JS, so could you tell me what exactly the ':visible' and the $(window).on('scroll',noscroll); do differently than the window.addEventListener property? – Cristian Mendoza Dec 16 '17 at 20:19
  • @CristianMendoza I update my answer .. this is all about pure javascript and jquery .. but while I always prefer and recommend to not combine both of them .. I already working with just jquery .. for sure no matter to use both of them but use just one of them make your code clear for you before being clear to anyone else – Mohamed-Yousef Dec 16 '17 at 20:25
  • @CristianMendoza I added a reference to everything you can check it .. Have a great day :) – Mohamed-Yousef Dec 16 '17 at 20:37