.click()
only binds to DOM nodes that exist at the time that you are binding the event. Your code assumes the events bind to DOM nodes that exist when the event itself happens.
This first line binds the click function only to the elements which currently have the '.selected' class -- so only the first anchor tag in your HTML has a click event bound to it. Call this event A:
$('.selected').click(function(){
$(this).removeClass('selected').addClass('selectoption');
On clicking that first anchor, you bind a new click event to all four of the anchors (because you've removed the '.selected' class from the first anchor and added '.selectoption'). Call this event B:
$('.selectoption').show().click(function(){
$(this).removeClass('selectoption').addClass('selected');
$('.selectoption').hide();
});
return true;
});
So after your first click on anchor 1, anchor 1 will fire both event A and event B when next clicked (binding a new event to the same element doesn't replace the existing event). The remaining anchors will fire event B only.
The behavior you actually want can be achieved by using .on() on a parent element -- this effectively binds the events to a CSS selector instead of to specific DOM nodes, so that when the user clicks the parent element, your code will check to see if the clicked target matches the class selector:
$('.parent')
.on('click', '.selected', function(evt) {
$(evt.target).removeClass('selected').addClass('selectoption');
}).on('click', '.selectoption', function(evt) {
$('.selected').removeClass('selected').addClass('selectoption');
$(evt.target).removeClass('selectoption').addClass('selected');
});
.selected {
background-color: #F00
}
.selectoption {
background-color: #0F0
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
<a href="#" class="selected">1</a>
<a href="#" class="selectoption">2</a>
<a href="#" class="selectoption">3</a>
<a href="#" class="selectoption">4</a>
</div>
(I removed the
hide()
and
show()
and changed the css rules to make it easier to see what's going on, but otherwise this behaves as I think you intended it to.)
So now two click events are bound to .parent
; the first will fire if the click target inside parent matches .select
, and the second will fire if the click target matches .selectoption
-- and unlike your original code the class matching is live, so you can safely change the classes on the DOM elements, or add new elements after binding the events and have the behavior follow the new classnames.
Read up on 'delegated events' here for more detail: http://api.jquery.com/on/