How To Chain Functions With Jquery
Solution 1:
So how about changing the activeItem to be on the li that has been clicked?
$('ul li').on('click',function(e){
e.preventDefault();
$(this).siblings().removeClass("activeItem");
$(this).addClass("activeItem");
});
JSFiddle here
Or even better, if you're in to chaining:
$('ul li').on('click',function(e){
e.preventDefault();
$(this).addClass("activeItem").siblings().removeClass("activeItem");
});
I should point out that I've added the following CSS:
ulli.activeItem
{
border: 1px solid #eab000;
}
ulli.activeItema
{
color:#eab000;
}
Solution 2:
You could use
$('ul li').first().css({
'border':'1px solid #eab000',
}).find('a').css({
'color':'#eab000'
});
$('ul li').on('click',function(e){
e.preventDefault();
$(this).css({
'border':'1px solid #eab000',
}).find('a').css({
'color' : '#eab000'
}).parent().siblings('li').css({
'border':'none',
}).find('a').css({
'color':'#404040'
});
});
You were using ".siblings" for the "inactive" links and then setting their anchor colours to your active colour. By setting the anchor before using "siblings" and then using "parent", you keep at a consistent level within the chain.
See your fiddle, fixed, here
However, the usage of specific colours within your code makes this kind of structure a bit brittle. Add/remove class as shown in the other examples is a more sustainable solution.
Solution 3:
Think about what comes out of each method and therefore what is going into the next :
css
= out: the same as in, so ignored for clarity
this
= out: the li
clicked
siblings
= in: li, out: the other li
s of the li
clicked
find
= in: the other li
s, out: all a
s under the other li
s
if you moved the find
up:
$(this).css({
'border':'1px solid #eab000',
}).find('a').css({
'color':'#eab000'
}).siblings('li').css({
'border':'none',
});
to match the .first
then the a will work, but the siblings won't as now:
this
= out: the li
clicked
find
= in: the li
clicked, out: all a
s under the clicked li
siblings
= in: the 'a', out: nothing (assumed)
so ideally, before the siblings you want some way to "cancel" the previous find
, luckily jquery has just this: .end()
You can apply this to either the original (find a
then go back to find siblings) or (find siblings then go back to find a
)
Here it is with the missing extra colour change
$(this).css({
'border':'1px solid #eab000',
}).find('a').css({
'color':'#eab000'
})
.end()
.siblings('li').css({
'border':'none',
}).find('a').css({
'color':'#404040'
});
Post a Comment for "How To Chain Functions With Jquery"