I am trying to work out, on click function remove class on and add new class off. when I click on the div again I would like to add class on again and remove class off which is not happening. I am not sure what reason this is not working. But if alert it works.
Here is my code. and Jsfiddle demo
$(".on").bind('click',function() {
$(this).removeClass('on').addClass('off');
alert('Hello World');
})
$(".off").bind('click',function() {
$(this).removeclass('off').addClass('on');
alert('Hello World');
})
$(".on")and$(".off")select elements currently in the DOM that match the selectors. So if you change the class of the element from.onto.offthen it will still fire the.onevent handler since that is what was bound to the element. You could use event delegation but I think.toggleClass()is probably a better implementation for you:Here is a demo: http://jsfiddle.net/LEvM4/1/
If you need to know which class is currently on the element you can check with
.hasClass():Here is a demo: http://jsfiddle.net/LEvM4/2/
A word about event delegation. You can also bind to an element that is an ancestor of the element you want to bind to, and delegate the event handler to the descendant element:
Here is a demo: http://jsfiddle.net/LEvM4/3/
A downside to event delegation is that when an event fires it requires more overhead. It’s usually best to try and bind directly to an element if possible. Normally you use event delegation if an element is not currently present in the DOM but you want to bind to future instances of an element.
Some documentation for ya:
.on(): http://api.jquery.com/on.toggleClass(): http://api.jquery.com/toggleClass.hasClass(): http://api.jquery.com/hasClass.delegate(): http://api.jquery.com/delegate