0

I have a popup which upon hoover requests data from the server to display. The only way I could prevent multiple popups, however, was to use synchronous ajax. I understand that synchronous ajax should rarely if never be used. Can this be done asynchronously? I am just learning about callbacks are needed, and have a feeling they are related. Thanks

(function( $ ){
    $.fn.screenshotPreview = function() {
        xOffset = 20;
        yOffset = 10;

        this.hover(function(e) {
            $.ajax({
                url:    'getPopup.php',
                success: function(data)
                {
                    $("body").append('<div id="screenshot">dl><dt>Name:</dt><dd>'+data.name+'</dd><dt>User Name:</dt><dd>'+data.username+'</dd></dl></div>');
                    $("#screenshot")
                    .css("top",(e.pageY - yOffset) + "px")
                    .css("left",(e.pageX + xOffset) + "px")
                    .fadeIn("fast");                    
                },
                async:   false,
                dataType: 'json'
            });
        },
        function() {
            $("#screenshot").remove();
        });
        this.mousemove(function(e) {
            $("#screenshot").css("top",(e.pageY - yOffset) + "px").css("left",(e.pageX + xOffset) + "px");
        });
    };
})( jQuery );
user1032531
  • 24,767
  • 68
  • 217
  • 387

1 Answers1

1

You want to add a flag saying whether or not you have started showing the popup:

(function( $ ){

    var showing = false;

    $.fn.screenshotPreview = function() {
        xOffset = 20;
        yOffset = 10;

        this.hover(function(e) {
          if(!showing){
            showing = true;
            $.ajax({
                url:    'getPopup.php',
                success: function(data)
                {
                  if(showing){
                    $("body").append('<div id="screenshot">dl><dt>Name:</dt><dd>'+data.name+'</dd><dt>User Name:</dt><dd>'+data.username+'</dd></dl></div>');
                    $("#screenshot")
                    .css("top",(e.pageY - yOffset) + "px")
                    .css("left",(e.pageX + xOffset) + "px")
                    .fadeIn("fast");
                  }                    
                },
                dataType: 'json'
            });
          }
        },
        function() {

            showing = false;

            $("#screenshot").remove();
        });
        this.mousemove(function(e) {
            $("#screenshot").css("top",(e.pageY - yOffset) + "px").css("left",(e.pageX + xOffset) + "px");
        });
    };
})( jQuery );
  • A low tech solution, but does exactly what I need. Thanks – user1032531 May 27 '12 at 18:18
  • After further investigation, looks like your solution is almost right. Needed to use Kolink's abort(). Did so by making variable ajax=$.ajax({..., and then in unhover ajax.abort() – user1032531 May 27 '12 at 18:51