简体   繁体   中英

jquery expand / collapse?

Im trying to make my jquery expand when clicked anywhere ( except the top left box ) and try to collapse when clicking only in the ( top left box )

http://jsfiddle.net/wzbAh/1/

HTML:

<div id="box">
    <div class="collapsed container" >
        <div class="nav" class="closed">0</div>
        box 1 - click me    
        <div class="expanded_content">
            extra content only for expanded state
        </div>
        <div class="collapsed_content">
            collapsed only content #1
        </div>
    </div>

    <div class="collapsed container">

        <div class="nav" class="closed">0</div>
        box 2 - click me    
        <div class="expanded_content">
            extra content only for expanded state
        </div>
    </div>
    <div class="collapsed container">

        <div class="nav" class="closed">0</div>
        box 3 - click me    
        <div class="expanded_content">
            extra content only for expanded state
        </div>
    </div>
</div>

JavaScript:

$("#box").delegate(".container", "click", function(e) {
    $(this).addClass("expanded");
});

$("#box").delegate(".container.expanded .nav ", "click", function(e) {

    $(this).addClass("collapsed");
});

Seems to be almost there but not quite, what would be the right way to do it? Since toggle seems not the option here.

Here you go mate...

$("#box").delegate(".container", "click", function(e) {
    if ($(e.target).hasClass("container")) {
        $(this).addClass("expanded");
    }
});

$("#box").delegate(".container.expanded .nav", "click", function(e) {
    $(this).parent().removeClass("expanded");
    e.stopPropagation();
});

The class "collapsed" is never removed so to remove the expanded state you need to use removeClass("expanded") , so it goes back to its initial state. Also, when the .nav element is clicked, the div you want to affect is the parent.

Finally, e.stopPropagation() stops the click firing both event handlers and removing the class and then adding it again.

Here's a working jsfiddle...

http://jsfiddle.net/wzbAh/11/

$("#box").delegate(".container", "click", function(e) {
    if (!$(e.target).is("div.nav")) {
       $(this).addClass("expanded");
    }
});

$("#box").delegate(".container .nav ", "click", function(e) {
    $(this).parent().removeClass("expanded").addClass("collapsed");
});

http://jsfiddle.net/jensbits/wzbAh/9/

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