Reputation: 1520
I have a three a
tags on a page. User can "select" only one.
Markup:
<div class="fl_near">
<span class="title">title</span>
<p>
<a id="filter_today" class="first_tb" style="display: block">
<span>text1</span>
</a>
<a id="filter_tomorrow">
<span>text2</span>
</a>
<a id="filter_afterTomorrow" class="last_tb selected" style="display: block">
<span>text3</span>
</a>
</p>
</div>
JS code:
$('.fl_near').find('a:not(.selected)').click(function () {
alert('1');
$('.fl_near').find('a').removeClass('selected');
$(this).addClass('selected');
});
This code not works properly. If I select first or second tag then all OK - style is switched, but alert shows anyway. If I select first then I can't select the last.
Where is a problem and why?
Thanks.
Upvotes: 0
Views: 63
Reputation: 3789
As it is now, you're not binding the click event to the link that is selected from start.
I would change:
$('.fl_near').find('a:not(.selected)').click(function () {
to
$('.fl_near a').click(function () {
Upvotes: 1
Reputation: 34596
The find
filter runs only once - it is not listening for successive clicks. Use event delegation for this - that way the filter will be applied when the click occurs, not, as currently, when you bind the event.
$('.fl_near').on('click', 'a:not(.selected)', function (evt) {
alert(1);
$(this).addClass('selected').siblings('a').removeClass('selected');
});
Note also I've simplified your add/remove-class line.
Upvotes: 1
Reputation: 160923
Because you don't bind click handler to the last element.
Try
$('.fl_near a').click(function () {
$(this).addClass('selected').siblings().removeClass('selected');
});
Upvotes: 1