I have two list items that, when clicked, should change classes from ‘.off’ to ‘.on’. Only one element should be ‘.on’ at a time so when one is already turned on and the other is clicked both elements should change classes from ‘.off’ to ‘.on’ and vice versa. If a list item with a class of ‘.on’ is clicked it should change classes to ‘.off’
The problem I am having is when a list item with class ‘.on’ is clicked it still runs the click function as if it had a class of ‘.off’
My html:
<ul>
<li><a href="about" class="off">ABOUT</a></li>
<li><a href="upload" class="off">SUBMIT</a></li>
</ul>
My javascript (running on jQuery 1.7.1)
$('.off').click(function(event) {
event.preventDefault();
$(".on").addClass("off").removeClass("on");
$(this).addClass("on").removeClass("off");
});
$('.on').click(function(event) {
event.preventDefault();
$(this).addClass("off").removeClass("on");
});
Does anyone know what is going on here? Is there something wrong in my code or have I encountered some sort of bug here?
The selectors you’re using to bind the event using
click()are used to select the elements to add the event handler to. The selector is not considered when the handler is run.You should be looking for something more like this:
You might want to make the
liselector more explicit by adding a class/id to theulorli‘s.To confuse things further, you could also do this (if you’re using jQuery > 1.7);
This is because the
.on()function works by attaching the event handler to the selected elements (document), and will only execute the handler (the function) on the event specified (click) if the element that the event originated from matches the selector.offat the time the event fired, not at binding time.