Skip to content Skip to sidebar Skip to footer

How To Chain Functions With Jquery

i want to make the clickable link active ( the border and the link a color). the border is switching on the clicked links but the color of the link is not changing. i want the acti

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");
  });

Link

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 lis of the li clicked find = in: the other lis, out: all as under the other lis

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 as under the clicked lisiblings = 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"