nuffsaid nuffsaid - 5 months ago 35
jQuery Question

addClass & removeClass not working

I have a menu, it should work as a click menu, so when clicking the button a menu will appear, and when clicking the button again, the menu should disapear, but i cant get it to work ?

I've got this script

<script type="text/javascript">
$(document).ready(function() {
$('#dropdown').click(function(){
setTimeout(function(){
$('#dropdown').attr("id", "dropdown2");
$('#dropmenu').addClass("open");
//$('#dropmenu').fadeIn('fast');
},500);
})
$('#dropdown2').click(function(){
setTimeout(function(){
$('#dropdown').attr("id", "dropdown");
$('#dropmenu').removeClass("open");
//$('#dropmenu').fadeIn('fast');
},500);
})
});
</script>


It works fint when adding the class, but then when im clicking the button again, it wont remove the class "open"

Answer

After you write $('#dropdown').attr("id", "dropdown2");, there is no #dropdown element for the code in the second handler to match.
Also, when you bind the second handler, there is no #dropdown2 element yet. (live events would solve that issue)

Instead, you should use the toggle event, which allows you to bind multiple click handlers that will execute every other click.

For example:

$(document).ready(function() { 
    $('#dropdown').toggle(
        function() {
            setTimeout(function(){
                $('#dropdown').addClass("open")
                              .fadeIn('fast');
            }, 500);
        },
        function() {
            setTimeout(function(){
                $('#dropdown').removeClass("open")
                              .fadeOut('fast');
            }, 500);
        }
    );
});