Reputation: 83
I have this working so far. I checked it in Firebug. I'm adding a class .selected to the clicked link in the click function. When I click a link the class of #dates a , changes to .selected, when I click another link the class of the previous link is being removed and the clicked link gets a class .selected
$( document ).ready(function() {
$('#dates li').click(function() {
$('#dates a').removeClass('selected');
$(this).children().addClass('selected');
});
This code is searching for the id of the list around the link. In most cases the id called, #year1943, #year1953 and so on. I want to use this id to check which year is being clicked/ has the class .selected.
function getSelectedYear() {
return $("#dates a.selected").parent().attr('id');
}
$(function(){
$('#dates li').click(function() {
var selectedYear = getSelectedYear();
if (selectedYear == "year1943"){
alert('The year is 1943');
}
});
});
});
this is my HTML markup
<ul id="dates">
<li id="all"><a href="#all" class="selected">1943-2013</a></li>
<li id="year1943"><a href="#1943">1943-1953</a></li>
<li id="year1953"><a href="#1953">1953-1963</a></li>
<li id="year1963"><a href="#1963">1963-1973</a></li>
<li id="year1973"><a href="#1973">1973-1983</a></li>
<li id="year1983"><a href="#1983">1983-1993</a></li>
<li id="year1993"><a href="#1993">1993-2003</a></li>
<li id="year2003"><a href="#2003">2003-2013</a></li>
</ul>
It seems that when the class .selected is added dynamically, Jquery can't find out which link has the class .selected. It can't notice the changes. I think I need something that re-scans the HTML/CSS markup to check which link has the class .selected.
Upvotes: 1
Views: 847
Reputation: 31
I'm not sure if I totally understang your problem, but if you want to get the ID of the LI element clicked, on click, can't you just use:
$('#dates li').click(function () {
$('#dates a').removeClass('selected');
$(this).children().addClass('selected');
var selectedYear = $(this).attr("id");
if (selectedYear == "year1943") {
alert('The year is 1943');
}
});
You could also use:
$('#dates li').on('click', function() {
var item = $(this);
$('#dates a').removeClass('selected');
item.children().addClass('selected');
if (item.attr('id') == 'year1943') {
alert('The year is 1943');
}
});
Upvotes: 1
Reputation: 12213
Try make on listener for the $('#dates li').click
event.
Try:
$('#dates li').click(function () {
$('#dates a').removeClass('selected');
$(this).children().addClass('selected');
var selectedYear = getSelectedYear();
if (selectedYear == "year1943") {
alert('The year is 1943');
}
});
function getSelectedYear() {
return $("#dates a.selected").parent().attr('id');
}
DEMO (click on the 1943 - 1953)
Upvotes: 1