简体   繁体   中英

Close Javascript Toggle

The following code is working to open data toggles on my site:

$(window).load(function(){
    $("a[data-toggle]").on("click", function(e) {
        e.preventDefault();  // prevent navigating
        var selector = $(this).data("toggle");  // get corresponding element
        $("article").hide();
        $(selector).show();
    });
});

And following is the HTML:

<a href="#" data-toggle="#uniquediv">Toggle</a>
<article id="uniquediv">
    Content in Toggle
</article>

I am trying to see what I need to change to allow the toggle to close when the link is clicked as well. Also it would be nice if another toggle is opened, then the open one will close so that only one stays open at a time.

Any help would be appreciated.

You can do something like this:

$("a[data-toggle]").on("click", function(e) {
e.preventDefault();  // prevent navigating
var selector = $(this).data("toggle");  // get corresponding element
if($(selector).is(":visible")) {
    $(selector).hide();
}

    else {
        $('article').hide();
        $(selector).show();

    }



});

Demo: http://jsfiddle.net/2bkhwhba/

Not sure about your CSS settings, but i made it like this:

a {
    display:block;
}

article {
    display:none;
}

Explanation, if needed - you have to check if element is visible, or not, on click, and consequently - show/hide it...

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