I have an a ajax method that hijacks every link in the HTML and preventDefault and then loads the loadPage function().
The method works on all other links that does not have a <img> inside. But when a <a> has a <img> inside the method clickEvent.target.href does not seem to work.
The var url in this instance returns undefined in the console, but on any other links it returns the href.
I'm guessing there is something wrong with I use the target method in this instance?
$('#container a').click(function(clickEvent){
var url = clickEvent.target.href;
if(url.match(urlWebServer)) {
clickEvent.preventDefault();
loadPage(url);
}
});
<div id="user_img">
<a href="somepage.html"><img src="img_user/self.jpg" class="self" /></a>
</div>
Yes, you shouldn't use the clickEvent.target because is the target that was clicked. In your case the target isn't the a but is the img it contains.
Events in fact bubble up, so you click the image and the click event propagates to the top (up to the a) and triggers the event delegate you provided.
The solution is to change that line to
var url = this.href;
Or if you prefer to get the value through jQuery use
var url = $(this).attr('href');
The first one is faster.
The solution is that this in the handler refers to the DOM element you attach the handler to. So this will refer to the a.
If you use jQuery to select and bind, why not use jQuery for the rest of your action?
$('#container a').click(function(event){
var url = $(this).attr('href');
if(url.match(urlWebServer)) {
event.preventDefault();
loadPage(url);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With