How to check which link is clicked using Javascript?

There are several ways to check which link is clicked . I will share the code with example.

CASE 1

In this case you just to need to call anchor tags by their class or by id using Javascript

check here for ID Selector (“#id”)

check here for Class Selector (“.class”)

You can simply use below code for this

HTML CODE

<style>
.anc{
  color:blue;
  border:1px solid black;
  padding:3px;
  margin:5px;
}
</style>

<a class="first anc" data-id="first">click 1</a>
<a class="second anc" data-id="second">click 2</a>
<div>
<h2>First Method</h2>
<span  class="first_method"></span>
</div>
<div>

SCRIPT CODE

$(document).ready(function(){
$(".first").click(function(){
$('.first_method').html($(this).data('id'));
    alert($(this).data('id'))
    });
$(".second").click(function(){
$('.first_method').html($(this).data('id'));
    alert($(this).data('id'))
    });
});

CASE 2

In this method we simply use tag to take using jquery . This method is very powerful to use when large number of anchor tags are there.

check how to get tags using javascript Element Selector (“element”)

HTML CODE

<style>
.anc{
  color:blue;
  border:1px solid black;
  padding:3px;
  margin:5px;
}
</style>
<a class="first anc" data-id="first">click 1</a>
<a class="second anc" data-id="second">click 2</a>

<div>
<h2>
Second Method
</h2>
<span class="second_method"></span>
</div>

SCRIPT CODE

/* second method if having multiple anchor on a single code */

$('a').click(function(){
$('.second_method').html($(this).data('id'));
alert($(this).data('id'))

});

WATCH DEMO HERE

You may also like...

1 Response

  1. Will says:

    Greetings from California! I’m bored at work so I decided to check out
    your blog on my iphone during lunch break. I enjoy the info
    you provide here and can’t wait to take a look when I get home.
    I’m surprised at how quick your blog loaded on my cell phone
    .. I’m not even using WIFI, just 3G .. Anyways, great blog!
    I couldn’t refrain from commenting. Very well written! Ahaa, its good conversation regarding this piece of writing here at this blog, I have read all that, so at this time me
    also commenting here. http://linux.com

    Feel free to surf to my blog: Will

Leave a Reply

Your email address will not be published. Required fields are marked *

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

codeforbetter will use the information you provide on this form to be in touch with you and to provide updates and marketing.