How do I make an AJAX call only once on JQuery.hover()?

dieterkp picture dieterkp · Aug 17, 2011 · Viewed 7.7k times · Source

I would like to display the results of an AJAX call in a div when the user hovers over it (i.e. replace the div contents with the results of the AJAX call). The basic functionality is to replace a dot on the page with a circle that contains content from the server when the user hovers over the dot, and show the dot again when they stop hovering. There may be many dots on the page, each with different circle content on hover.

I have it working, but I notice that the AJAX call is getting repeatedly called while the user is hovering over the given div. How can I prevent repeated calls?

I have tried various usages of .one and .unbind('mouseenter', 'mouseleave') but haven't gotten it to work right yet.

Here's what I have right now (the hover behavior works right for the user but causes repeated calls to the backend).

<div class="box1" s='<%=value1 %>' t='<%=value2 %>'>
   <div id="circle" style="display: none;">
   </div>
   <div class="dot" id="dot">
      <img src="orangeDot.png" />
   </div>
</div>

and the script:

<script type='text/javascript'>
    $(document).ready(function () {
        $(".box1").hover(function () {
            var source = $(this).attr('s');
            var target = $(this).attr('t');
            $('#dot').attr("style", "display: none;");
            $('#circle').hide().load('/GetCircle?s=' + source + '&t=' + target).show();
        }, function () {
            $('#circle' + divid).attr("style", "display: none;");
            $('#dot' + divid).attr("style", "display: inline-block;");
        });
    });
</script>

Answer

Matt Stein picture Matt Stein · Aug 17, 2011

Why not just have a boolean flag like var ajaxed = false and switch it to true after the request is completed once? Then just wrap your hover action in a check for ajaxed.