1

I'm trying to use jquery and click() to grab the url of an image link once its clicked. The html looks like this.

<div class="lp-element lp-pom-image" id="lp-pom-image-167" >
<a href="http://url.com/page" target=""><img src="/image.jpg" alt=""></a>
</div>

The javascript I'm using so far looks like this but it isn't grabbing the url of the clicked image link. The url needs to be passed to where the variable this is.

jQuery(function() {
jQuery("#lp-pom-image-167").click(function() {
trackOutboundLink(this, 'AddToCart', 'Bottom CTA');
return false;
});
}); 

How do I pull the href url with the appropriate base URI? ie. "http://url.com/page"?

EDIT:clarified what i am trying to pull out.

incognito2
  • 1,024
  • 3
  • 13
  • 20

3 Answers3

1

I'd suggest (though untested):

$('.lp-pom-image').click(function(e){
    e.preventDefault(); // stops the default action,
                        // without preventing propagation/bubbling
    trackOutboundLink($(this).find('img').prop('src'), 'AddToCart', 'Bottom CTA');
});
David Thomas
  • 249,100
  • 51
  • 377
  • 410
  • Similar to mine example, but you are using .prop() instad of .attr(). Note: As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes. http://api.jquery.com/prop/ – Maksym Kozlenko Feb 19 '13 at 00:49
  • @Maksym: yes, I know. But thanks for taking the time to point that out. I assumed that he'd want the full URL (hence `prop()`) rather than retrieving a potentially relative URL that might be in the attribute (which he'd get with `attr()`). – David Thomas Feb 19 '13 at 00:51
  • this worked although i switched out find('img') with find('a'). thanks! – incognito2 Feb 19 '13 at 01:07
0
jQuery(".lp-pom-image").click(function() {
  console.log($("img", this).attr("src"));
  return false;
}); 

See a working demo at http://jsbin.com/ebicax/4/

Maksym Kozlenko
  • 10,273
  • 2
  • 66
  • 55
0

Use code below instead of this if you want get a url:

$(this).find("a").attr('href')

or this code if u want get img src:

$(this).find("a img").attr('src')
WooCaSh
  • 5,180
  • 5
  • 36
  • 54