简体   繁体   中英

jQuery - Toggle div class on click

No, this is not a straight forward toggle question. I am aware of the toggle() functions and how to simply hide/show a div. Imagine a box with a label inside:

<div class="section hidden">
    <div class="section-legend">My Section</div>
</div>

When you click anywhere on the entire div, it should remove class hidden . The box then looks expanded. Now that the box is not of class hidden it should not be clickable.

Instead, when you click the div.section-legend it should add class hidden to the main div again. Obviously the click event for the legend needs to stopPropagation(). Now the legend should not be clickable anymore and once again you must click the entire div to open it.

I can't get anything to work properly, and I know this is stupid code:

$(document).ready(function() {

    $('.section.hidden').click(function() {
        $(this).removeClass('hidden');
        $(this).find('.section-legend').click(function(e) {
            $(this).parent().addClass('hidden');
            e.stopPropagation();
        });
    });

    $('.section-legend').click(function(e) {
        $(this).parent().addClass('hidden');
        e.stopPropagation();
        $(this).parent().click(function() {
            $(this).removeClass('hidden');
        });
    });

});

$('.section-legend').live('click',function(){
    $(this).parent().toggleClass('hidden');
});

This is assuming the section-legend is just as large as it's container in 'hidden state'.

EDIT: changed some code, solution is this:

$('.section').live('click',function(){
    $(this).removeClass('hidden');
});
$('.section-legend').live('click',function(){
    $(this).parent().toggleClass('hidden'); return false;
});

return false did the trick! demo: http://jsfiddle.net/RUfN7/2/

First add an onclick event on the div that needs clicking:

<div id="myDiv" class="section hidden">
    <div class="section-legend" onclick="function1();">My Section</div>
</div>

And add this javascript to the html

<script language="JavaScript">
    function function1(){
        document.getElementById("myDiv").removeAttribute("class");

    }
</script>
$('.section').click(function() {
    $(this).removeClass('hidden');
});

$('.section-legend').click(function(e) {
    var $parent = $(this).parent();
    if(!$parent.hasClass('hidden')) {
        $parent.addClass('hidden');
        return false;
    }
});

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