So I’m trying to create a tooltip and want it so that while creating it it will add a click event to the body so that whenever anything on the body is clicked then the tooltip goes away. Theoretically this would propogate so that if a user clicks on a link then the tooltip would disappear and the user would travel to wherever the link points to.
The issue I’m running into is for some reason the following is not working. I’m getting the ‘here’ even before I click anywhere and it triggers the tooltip removal almost directly after it gets created so no tooltip appears. Any thoughts on how to do this.
$("a").click(function(event){
event.preventDefault();
$(document.body).click(function(){
$('.tooltip').remove();
console.log('here');
})
var text = $(this).attr('title');
var tooltip = $('<div class="tooltip">' + text + '</div>');
$(document.body).append(tooltip);
});
Here’s a JS Fiddle: http://jsfiddle.net/fgRTa/ You should click on link 2 first to see it work, else if you do link 1 then link 2, the body has the click event already on it so it won’t allow the adding of a tooltip. Theoretically I’d like that issue to disappear as well so the click event would be removed when I do a click one time, but that’s a side issue.
Thanks
It’s because the current click hasn’t stopped propagating when you add the click handler to the body.
Try using
event.stopPropagation();.A Fiddle, for your consideration http://jsfiddle.net/fgRTa/2/