Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click event on the span appended during the mouseover is not firing

I append a span to a div on mouseover, and I simply want to trigger a click on the nested span. It feels like I've tried everything out of luck.

http://jsfiddle.net/NHHSX/1/

I've found a couple of similar but they unfortunately didn't work out either.

like image 388
lynx_vbg Avatar asked Jun 10 '13 14:06

lynx_vbg


1 Answers

Change your mouseover to mouseenter and use event delegation

$('.container').on('mouseenter', function (e) {
    $(this).append('<span class="span1">I want this to be clickable..</span>');
}).on('mouseleave', function (e) {
    $(this).find('.span1').remove();
});

$('.container').on('click', '.span1', function () {
    alert("click");
});

Demo

Using mouseover, it gets triggered even when you hover over the child span and it keeps on removing and appending the span.

from doc

The mouseenter event differs from mouseover in the way it handles event bubbling. If mouseover were used in this example, then when the mouse pointer moved over the Inner element, the handler would be triggered. This is usually undesirable behavior. The mouseenter event, on the other hand, only triggers its handler when the mouse enters the element it is bound to, not a descendant. So in this example, the handler is triggered when the mouse enters the Outer element, but not the Inner element.

like image 168
PSL Avatar answered Nov 01 '22 01:11

PSL