Raphael Jeger Raphael Jeger - 5 months ago 45
jQuery Question

Select2 fire event on mouseenter of results

I need to reset a timer that's closing the parent DIV containing a select2-container on mouseleave.

This does not fire:

$('.select2-dropdown').on('mouseenter', function(e){
console.log('in');
clearInterval( $(this).data('timer') );
});


I tried all possible selectors on the DOM but it does not fire.

Thanks!

Answer

You do not appear to be setting this handler correctly.

The dropdown is only generated by Select2 when it opens, and it is removed after it closes. So you can't just set the handler once and forget about it, unless you use event delegation.

$('body').on('mouseenter', '.select2-results__option', function(e){
   console.log('in');
   clearInterval( $(this).data('timer') );
});

So it will actually catch the event on the body and then check if it came from the option in the results.

The other option is to keep your current handler, but bind it during select2:open (on the select) instead of ready (on the document). This may also require unbinding it during select2:close.