Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - making a clicked link underlined

just starting to get my hands dirty with the jQuery goodness and the first task i'm trying to tackle is to underline a link after it has been clicked. Naturally, after a different link in the same div was clicked the previous one is no longer underlined...

Regards

like image 482
dexter Avatar asked Mar 13 '26 12:03

dexter


2 Answers

So basically, you are wanting a kind of navigation menu that changes the style of the link once clicked. First, make a style that just underlines:

<style type="text/css">
a.currentlyActive
{
  text-decoration: underline;
}
</style>

The code you will be modifying is...

<a class="navigation" href="#">My First Link</a>
<a class="navigation" href="#">My Second Link</a>
<a class="navigation" href="#">My Third Link</a>

Just a few links with some type of class that denotes that it is the links u want to underline and not underline.

Next, add a little jQuery magic to apply the style upon clicking. And at the same time, you will want to remove the style from all others.

<script type="text/javascript">
$(function() {
  $('.navigation').click(function() {
    // this removes the underline class from all other ".navigation" links.
    $('.navigation').removeClass('currentlyActive');

    // this makes the one that was clicked underlined
    $(this).addClass('currentlyActive');
  });
});
</script>

And, that's it. I tried to as verbose as possible to explain what each step does. Obviously, you can makes the class names shorter and remove the comments to make it small and lean.

like image 95
eduncan911 Avatar answered Mar 16 '26 08:03

eduncan911


$("a").click(function() {
  var $this = $(this);
  $this.closest("div").find("a").removeClass("underlined");
  $this.addClass("underlined");
});

Then, of course, you need to have a class called "underlined", that underlines the links.

like image 42
EmKay Avatar answered Mar 16 '26 08:03

EmKay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!