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');
});
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.
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.
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");
}
});
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With