jquery click change class
Asked Answered
E

3

6

I am studying jquery, I want make a effection as: first click, slider down the div#ccc and change the link class to 'aaa'; click again, slider up the div#ccc and change the link class back to 'bbb'. now slider down can work, but removeClass, addClass not work. how to modify so that two effection work perfect? thanks.

<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>
Electrolyze answered 19/5, 2011 at 21:35 Comment(0)
U
5

You need to use a single toggle event. You are setting the click event twice and that won't work.

jsfiddle

Unstop answered 19/5, 2011 at 21:39 Comment(0)
F
6

Use toggle instead of show/hide and toggleClass instead of add/remove, and merge into a single click event. Something like this (untested and probably doesn't work):

$("#click").click(function() {
    $("#ccc").toggle().animate();
    $(this).toggleClass('bbb aaa');
});
Fiorenza answered 19/5, 2011 at 21:42 Comment(1)
$(this).toggleClass('bbb aaa'); would be even better.Lasalle
U
5

You need to use a single toggle event. You are setting the click event twice and that won't work.

jsfiddle

Unstop answered 19/5, 2011 at 21:39 Comment(0)
A
1

You are looking for the toggle event, it appears.

$(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');
        });
    });
Alicyclic answered 19/5, 2011 at 21:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.