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.
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");
});
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.
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