ggdx
ggdx

Reputation: 3064

Simple jQuery conflict

I am (very) new to jQuery so please be gentle but I cannot seem to get the basic script below to work properly.

The immediate class when loaded is .menuFlyout and when it's clicked it changes as needed however the second part to change it back does not work. noConflict() doesn't help.

Thanks in advance for any help.


jQuery(document).ready(function() {
    jQuery('.menuFlyout').click(function(){
        jQuery('.menuFlyout').addClass('closeFlyout');
        jQuery('.menuFlyout').removeClass('menuFlyout');
    });
    jQuery('.closeFlyout').click(function(){
        jQuery('.closeFlyout').addClass('menuFlyout');
        jQuery('.closeFlyout').removeClass('closeFlyout');
    });
});

Upvotes: 0

Views: 83

Answers (2)

Rashedul.Rubel
Rashedul.Rubel

Reputation: 3584

check the class name whether have you spelled correctly. check in firebug as well. try as follows to see whether it works:

jQuery(document).ready(function() {
    jQuery('.menuFlyout').live('click',function(){
        jQuery('.menuFlyout').addClass('closeFlyout');
        jQuery('.menuFlyout').removeClass('menuFlyout');
    });
    jQuery('.closeFlyout').live('click',function(){
        jQuery('.closeFlyout').addClass('menuFlyout');
        jQuery('.closeFlyout').removeClass('closeFlyout');
    });
});

Hope this helps, thanks

Upvotes: 2

Claudio Redi
Claudio Redi

Reputation: 68400

Try with this

jQuery(document).ready(function() {
    jQuery(document).on('click','.menuFlyout', function(){
        jQuery('.menuFlyout').addClass('closeFlyout');
        jQuery('.menuFlyout').removeClass('menuFlyout');
    });
    jQuery(document).on('click','.closeFlyout', function(){
        jQuery('.closeFlyout').addClass('menuFlyout');
        jQuery('.closeFlyout').removeClass('closeFlyout');
    });
});

The problem with your code is that there is no element with class closeFlyout when you attah the handler. You need to delegate the click handler using on method (see section "Direct and delegated events" for more details ).

Using event delegation should fix your problem but as a side note here you have 2 improved versions of your code (as sugggested by @wirey and @h0tw1r3)

jQuery(document).ready(function() {
    jQuery(document).on('click','.menuFlyout', function(){
        jQuery(this).addClass('closeFlyout').removeClass('menuFlyout');
    });
    jQuery(document).on('click','.closeFlyout', function(){
        jQuery(this).addClass('menuFlyout').removeClass('closeFlyout')
    });
});

or

jQuery(document).ready(function() {
    jQuery(document).on('click','.menuFlyout, .closeFlyout', function(){
        jQuery(this).toggleClass('closeFlyout');
        jQuery(this).toggleClass('menuFlyout');
    });
});

Upvotes: 3

Related Questions