mouseover/mouseout events with ajax requests

598 views Asked by At

I just recently ran into this issue and I wish I could get some top ideas from here. Here is how my code looks like:

$(document).on('mouseover', '#element', function(){
    $.ajax({
          // generate hover view
     })
});

$(document).on('mouseout', '#element', function(){
     // remove hover view
});

The correct execution order would be mouseover - generate view - mouseout - hide view.

However since the view part depends on ajax, there is a chance that mouseout event gets fired before the ajax call finishes if the user hovers super fast. In that case, after the ajax call is completed, the view is just going to sit in the DOM without going away, since the mouseout event is already fired.

1

There are 1 answers

0
pegla On

Did you try using Promises? This will need to be tweaked but something like:

$.when( $.ajax( "someajaxfile.txt" ) ).then(function( data, textStatus, jqXHR ) {
  $(document).on('mouseout', '#element', function(){
     // remove hover view
});
});

You may need to unbind mouseout as well.