简体   繁体   中英

My mobile menu Jquery script only runs once

Hi I'm new to jquery and just trying to put a simple script together to show/hide my mobile menu on click. It works fine however, it only works once until you refresh your browser.

Jquery:

$(document).ready(function () {
  //your code here
    $(".nav").addClass("hidenav");
    $(".menutrigger").click(function () {
        $(".nav").removeClass("hidenav").addClass("slidenav");

$(".menutrigger").click(function () {
        $(".nav").removeClass("slidenav").addClass("hidenav");
        });

        });
});

CSS:

@media (max-width: 767px) {
    .slidenav {
        display: block;
    }
    .hidenav {
        display: none;
    }
}

It is because you are defining multiple click events

This should work

$(document).ready(function()
    {
        //your code here
        $(".nav").addClass("hidenav");
        var flag = 0;
        $(".menutrigger").click(function()
        {
            if(flag == 0)
            {
                flag = 1;
                $(".nav").removeClass("hidenav").addClass("slidenav");
            }
            else
            {
                flag = 0;
                $(".nav").removeClass("slidenav").addClass("hidenav");
            }

        });
    });

declaring multiple onClick events won't work and will be overridden by last one. you can do all those things in on onclick callback by checking whether your class is there or not

$(document).ready(function () {
  //your code here
    $(".nav").addClass("hidenav");
    $(".menutrigger").click(function () {
        if ($(".nav").hasClass("hidenav")){
           $(".nav").removeClass("hidenav").addClass("slidenav");
        } else if ($(".nav").hasClass("slidenav")){
           $(".nav").removeClass("slidenav").addClass("hidenav");
        }
    });
});

Have you tried toggleClass ?

$('.menutrigger').click(function (e) {
     $('.demo').toggleClass("hidenav");
});

it will compress your code to just 1 line.

have a look at this fiddle

To know more about .toggleClass(). see the jQuery API doc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM