1

I'm learning jQuery, and I can't seem to make this work.

I have a hamburguer button toggler, which when clicked, it should open a menu panel. At the same time, it should call a function to prevent scroll of the document.

I have 2 functions, one to disable the document scroll, other to enable it back:

function disableScroll(){...}
function enableScroll(){...}

And here I have the toggler icon click event:

$("#main-nav-toggler").click(function() {
        $("#main-nav-menu").toggleClass("menu-show");
        disableScroll();
});

The problem is, I don't know how to toggle between the 2 scroll functions within the toggler click event. I only know how to call one function, I don't know how to toggle between the 2 on click.

2 Answers 2

2

You can use the hasClass() function to check which function you need to call.

$("#main-nav-toggler").click(function() {
        $("#main-nav-menu").toggleClass("menu-show");
        $("#main-nav-menu").hasClass("menu-show") ? disableScroll() : enableScroll();
});

function disableScroll(){
  console.log("disable scroll");
}
function enableScroll(){
  console.log("enable scroll");
}
#main-nav-menu {
  display: none;
}

#main-nav-menu.menu-show {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main-nav-toggler">toggler
</div>
<div id="main-nav-menu">menu
</div>

Sign up to request clarification or add additional context in comments.

1 Comment

That's exactly what I needed. I just started to learn js and jQuery, so I need to study it more, I didn't knew about the hasClass(). Thank you very much mate!
2

You can check if main-nav-menu has a class of .menu-show

$("#main-nav-toggler").click(function() {
    $("#main-nav-menu").toggleClass("menu-show");
    if($("#main-nav-toggler").hasClass("menu-show")){
        disableScroll();
    } else{
        enableScroll()
    }
 });

Jquery hasClass() documentation: https://api.jquery.com/hasClass/

1 Comment

Thank you very much, I didn't knew about hasClass yet, just started learning jQuery.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.