Jquery click change class

I am learning jquery, I want to make an effect: first click, slider down div # ccc and change the link class to 'aaa'; press again, highlight div # ccc and change the link class to "bbb". now the slider can work, but removeClass, addClass does not work. how to change so that two effective works are ideal? thank.

<script type="text/javascript" src="jquery.js"></script> 
<script type="text/javascript">
jQuery(document).ready(function(){              
$("#click").click(function() {
    $("#ccc").slideDown('fast').show();
    $(this).removeClass('bbb').addClass('aaa');
});
$("#click").click(function() {
    $("#ccc").slideDown('fast').hide();
    $(this).removeClass('aaa').addClass('bbb');
});
});
</script>
<style>
#ccc{display:none;}
</style>
<div id="click" class="bbb">click</div>
<div id="ccc">hello world</div>
+3
source share
3 answers

You need to use one switch event. You set the click event twice, and that won't work.

jsfiddle

+4
source

Use toggle instead of show / hide and toggleClass instead of adding / removing and combine into one click event. Something like this (untested and probably not working):

$("#click").click(function() {
    $("#ccc").toggle().animate();
    $(this).toggleClass('bbb aaa');
});
+3

, .

$(document).ready(function () {
    $('div#click').toggle(
        function () {
            $('div#ccc').slideDown('fast').show();
            $('div#click').removeClass('bbb').addClass('aaa');
        },
        function () {
            $('div#ccc').slideDown('fast').hide();
            $('div#click').removeClass('aaa').addClass('bbb');
        });
    });
+1

All Articles