Search code examples
javascriptjqueryajaxjqvmap

JQVMap - Ajax call on hover, issue with label


I am using JQVMap for displaying countries.

If the country is hovered it displays count via ajax which is correct.

The issue is when I hover many countries fast it appends into one label where I stoped, so basically it "stacks" the labeling.

Example:

I hover too many countries at once. I stop for example at Italy, all the "school counts" will apend there.

Here is my JS code

$(document).ready(function(){
jQuery('#vmap').vectorMap({
    map: 'world_en',
    backgroundColor: null,
    color: '#ffffff',
    hoverOpacity: 0.7,
    selectedColor: '#666666',
    enableZoom: true,
    showTooltip: true,
    values: sample_data,
    scaleColors: ['#C8EEFF', '#006491'],
    normalizeFunction: 'polynomial', 
    onLabelShow: function (event, label, code) {

        if(sample_data[code] > 0) {
            //console.log(code);
            $.getJSON('/ajax/admin/ajaxcallpage', {country_key: code}, function(data) {
                //var school_count = 0;
                school_count = data;
                label.append(': ' + school_count + ' Schools'); 

            });
        }
    }
});
});

Solution

  • The issue is because all the AJAX requests are still fired, and once they complete all the results are added to the label. You can cancel the previous request by calling abort() on the jqXHR returned from $.getJSON. Try this:

    var lastRequest; // variable to store the previous request
    
    jQuery('#vmap').vectorMap({
        map: 'world_en',
        backgroundColor: null,
        color: '#ffffff',
        hoverOpacity: 0.7,
        selectedColor: '#666666',
        enableZoom: true,
        showTooltip: true,
        values: sample_data,
        scaleColors: ['#C8EEFF', '#006491'],
        normalizeFunction: 'polynomial', 
        onLabelShow: function (event, label, code) {
            if (sample_data[code] > 0) {
                lastRequest && lastRequest.abort(); // abort the previous request
    
                lastRequest = $.getJSON('/ajax/admin/ajaxcallpage', {
                    country_key: code
                }, function(data) {
                    school_count = data;
                    label.append(': ' + school_count + ' Schools'); 
                });
            }
        }
    });