tags:

views:

59

answers:

2

I understand that I can use the .click() method on a hyperlink element. But how do I know which element was clicked? First I have to gain reference to the hyperlink's ID.

So lets say I have a page of hyperlinks like this in view source:

<a href="addButton1" href="...someurl"><img src="somebutton"></a>
<a href="addButton2" href="...someurl"><img src="somebutton"></a>
<a href="addButton3" href="...someurl"><img src="somebutton"></a>
<a href="addButton4" href="...someurl"><img src="somebutton"></a>

when a user clicks addButton1, how do I even know it's addButton1 that was clicked in the first place so that I can now apply a .click() event on it?

+5  A: 

To observe click event for all links on a page:

$("a").click(function (e) { 
      // this function fires anytime a hyperlink is clicked

      e.preventDefault();

      // reference $(this) to get at the specific 
      // link that fired the event, such as:
      alert($(this).attr('href')); // display href value of the hyperlink
    });

To observe click events for a subset of links on a page:

Add a class to your hyperlink tags. Example: <a class="observe" href="#">

And change the above function event signature to:

$("a.observe").click(function (e) { ... });
JonathanK
what if I don't want to run javascript for every hyperlink? I'd be making the user check and run this function every time. There is only a subset of hyperlinks that this function will apply to outside the many other hyperlinks on my page (top nav, left nave, etc.).
CoffeeAddict
I've edited the solution to demonstrate this approach now.
JonathanK
A: 

The best way to differentiate between links is to add a class or id to them. Then you can set event handling like so:

HTML:

<a href="javascript:" class="myClass" id="myId">Click here!</a>

jQuery can be done in one of two (ok, there are more than two, but here are two) ways:

$('#myId').click(function() { doSomething() });
$('.myClass').click(function() { doSomething() });
Jason