Reputation: 711
I have this function which gets executed when a link is clicked. But there seems to be an issue with that. When I use some text for the same link.
The function seems to get executed well, but except when I place an image in the same place, then event handler function doesn't seem to be working.
I created a Fiddle for this one: http://jsfiddle.net/bkvirendra/5QqUB/
When the link is clicked a ul list is shown. And when the user clicks anywhere instead of the link the ul list gets disappeared. So when I place an image instead of the text its doesn't seem to be working! How can I show the same ul list when the image is clicked?
Upvotes: 1
Views: 304
Reputation: 11342
It happens because e.target
return the clicked element, so it's returning the image. Try this code:
$("html").click(function(e) {
if (e.target == document.getElementById("a") || e.target.nodeName=='IMG') {
$(".item").show();
//alert(1);
} else {
$(".item").hide();
//alert(2);
}
});
Upvotes: 0
Reputation: 337530
The problem is because when you click the image, the event target becomes the img
tag, not the a
tag.
Try this:
$(".item").hide();
$("#a").click(function(e) {
e.stopPropagation();
$(".item").show();
});
$(document).click(function() {
$(".item").hide();
});
You should also consider removing the $(".item").hide()
line and using display: none
in CSS instead.
Upvotes: 1