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.

7
  • 1
    $(this).children("a img").attr('src') should do the trick. Commented Feb 19, 2013 at 0:34
  • 2
    <worried> Hope you don't intend to copy paste this(any) JS code like this one 200 times for all your #lp-pom-image-NNN elements.... </worried> Commented Feb 19, 2013 at 0:36
  • @Supericy jQuery .prop should be used instead of .attr. Commented Feb 19, 2013 at 0:40
  • 1
    @Mooseman please paste an official link where we can read this. Commented Feb 19, 2013 at 0:41
  • 1
    @SheikhHeera specially this answer: stackoverflow.com/a/7572855/390747 Commented Feb 19, 2013 at 0:51

3 Answers 3

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');
});
Sign up to request clarification or add additional context in comments.

3 Comments

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. api.jquery.com/prop
@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()).
this worked although i switched out find('img') with find('a'). thanks!
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')

Comments

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.