简体   繁体   中英

JQuery stop show/hide on click

I have a code snippet that shows a div once you click the menu item, there are different divs on this space and what the menu does is hide the one that was there before and show the new one, the problem is when I click on the same menu item it shows the current div again and I want to stop that from happening, it should only show the animation if it's not the current one, if it is nothing should happen.

Here is the code snippet:

var curPage="";
$("#menu a").click(function() {
     if (curPage.length) { 
        $("#"+curPage).hide("slide");
     }
     curPage=$(this).data("page");
     $("#"+curPage).show("slide");
});      

And here is a demo of how it's occuring now: https://jsfiddle.net/Lfsvc1ta/

Just add an additional check to see whether curPage is the same as the clicked page.

var curPage;
$("#menu a").click(function () {
    var page = $(this).data("page");
    if (curPage && page != curPage) {
        $("#" + curPage).stop().hide("slide");
    }
    $("#" + page).stop().show("slide");

    curPage = page;
});

Demo: Fiddle

Check what data-page is clicked first bro.

var curPage="";
$("#menu a").click(function() {
    var newPage = $(this).data("page");
    if (newPage !== curPage) {
         $("#"+curPage).hide("slide");
         $("#"+newPage).show("slide");
         curPage = newPage;
    }         
});   

You have to check what the before page was, adding a variable.

var curPage="";
$("#menu a").click(function() {
     var page=$(this).data("page");
     if (curPage!=page && curPage.length) { 
        $("#"+curPage).hide("slide");
         curPage=$(this).data("page");
     }
     $("#"+curPage).show("slide");
});   

Like this fiddle https://jsfiddle.net/7b1wh70h/

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