Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handler doesnt get an event

Tags:

html

jquery

css

I have this code : if you try to click on Button 2 or 3 you can see the right effect. Now, go back and try to click on Button 1 : nothing happens.

Why? Thanks

$('.navigatorUserButtonOff').click(function(e){
    e.preventDefault();
    $('.navigatorUserButtons').find('.navigatorUserButtonOn').removeClass().addClass('navigatorUserButtonOff');
    $(this).removeClass().addClass('navigatorUserButtonOn');
});
like image 586
markzzz Avatar asked Dec 05 '22 22:12

markzzz


2 Answers

The reason why it's not working

Because this selector you use at the beginning to bind click handler

$('.navigatorUserButtonOff')

selects only the second and third button. So you're binding click handler only them couple. First button doesn't have this class hence no click handler is bound to it.

Two posible solutions

  1. use delegate (you could use live as well but using delegate is better and works faster)

    $(".navigatorUserButtons").delegate(".navigatorUserButtonOff", "click", function(evt){
        evt.preventDefault();
        // remove and add classes as desired
    });
    

    This one will be a bit problematic because click handler will only be working on the off state buttons which means that clicking on the on state button will execute default browser behaviour that happens when you click a link. This is definitely not desired in your situation and you'll have to bind a click event to a on button as well to prevent default behaviour.

  2. A much better approach is to use a separate class that defines a button and a different one for its on/off state:

    <a class="navigatorUserButton on">...</a>
    

    And you don't need off state at all neither delegated events:

    $(".navigatorUserButton").click(function(evt){
        evt.preventDefault();
        var $this = $(this);
        if (!$this.hasClass("on"))
        {
            $this.siblings(".on").removeClass("on");
            $this.addClass("on");
        }
    });
    
like image 165
Robert Koritnik Avatar answered Dec 08 '22 03:12

Robert Koritnik


The reason this occurs is because the code which hooks up the events only runs once. At the time it runs button 2 and 3 meet the criteria and succesfully hookup the event. Later changes to the DOM qualify button 1 for the filter but it doesn't run again and hence button #1 doesn't get hooked up.

You can fix this by using the live function in jQuery.

$('.navigatorUserButtonOff').live('click', function(e){
  e.preventDefault();

  $('.navigatorUserButtons').find('.navigatorUserButtonOn').removeClass().addClass('navigatorUserButtonOff');
  $(this).removeClass().addClass('navigatorUserButtonOn');
});

Here is a link to a working version

  • http://jsfiddle.net/qGMfJ/1/
like image 20
JaredPar Avatar answered Dec 08 '22 03:12

JaredPar