0

After reading this Q&A I was able to pass the URL of a specific div to jQuery upon clicking the link. However, I have multiple links of the page and I want to pass their individual href values to jQuery upon clicking. Right now the code selects all links on the page:

jQuery(document).ready(function(){
  jQuery(".view-frontpage a").click(function (event) {
    href = $('.view-frontpage a').attr('href');
    event.preventDefault();
    alert(href);
   });
});

The result of this currently is that it pops up a dialog displaying the href property of the first link on the page, regardless of which link is clicked. How do I change this to give me the href of the link that has just been clicked?

Community
  • 1
  • 1
beth
  • 1,916
  • 4
  • 23
  • 39

2 Answers2

7

This should work. Change:

href = $('.view-frontpage a').attr('href');

To:

href = $(this).attr('href');
Sean Bright
  • 118,630
  • 17
  • 138
  • 146
1

First, it's a good idea to use event delegation so you don't actually create a handler for every link on your page.

In your case, jQuery binds this inside your click handler to the click event target (the element that's been clicked on), so you need to do href = $(this).attr('href'); to get the href of the link you need.

Here is the full code using the new jQuery on() function (available since 1.7)

$(document).on('click', '.view-frontpage a', function(e) {
    alert($(this).attr('href'));

    e.preventDefault();
    return false;
});​​​
Dmitry Pashkevich
  • 13,431
  • 9
  • 55
  • 73