Search code examples
javascriptjqueryjvectormap

How to show tooltip only if a region is clicked in jVectorMap, and let it open?


I'm using this jVectorMap. By default, it shows tooltip on hover.

Here is what I'm trying to achieve -

  1. Show tooltip only on click (partially working but tooltip should be be above the mouse cursor. I couldn't figure out how to get mouse cursor position.)
  2. Let the tooltip opens until user explicitly clicks on close.

Code: jsfiddle

$('#map').vectorMap({
    map: "us_aea_en",
    backgroundColor: "transparent",
    regionStyle: {
        initial: {
            fill: "#818486"
        }
    },
    onRegionClick: function (e, code) {
        var map = $('#map').vectorMap('get', 'mapObject');        
        map.tip.show();
        map.tip.html(code + "<p>Click to Close</p>");
    },
    onRegionTipShow: function (e, tip, code) {
        e.preventDefault();
    }
});

Desire Behavior

enter image description here


Solution

  • I got it working the way you want and updated your fiddle: http://jsfiddle.net/inanda/ufhz316z/5/

    Javascript

     $('#map').vectorMap({
        map: "us_aea_en",
        backgroundColor: "transparent",
        regionsSelectable: true,
        regionsSelectableOne: true,
        regionStyle: {
            initial: {
                fill: "#818486"
            },
            selected: {
                fill: "#C0C0C0"
          }
        },
        onRegionClick: function (e, code) {
            var map = $('#map').vectorMap('get', 'mapObject');
            var customTip=$('#customTip');
    
            customTip.css({
              left: left,
              top: top
            })
    
            customTip.html(map.tip.text());
          customTip.show();
          customTip.append(code + "<p>Click to Close</p>");
            customTip.children("p").click(function(){
                map.clearSelectedRegions();
               customTip.hide(); 
            }) 
    
        },
        onRegionTipShow: function (e, tip, code) {
            e.preventDefault();
        }
    });
    
    var left,top;
    $('#map').vectorMap('get', 'mapObject').container.mousemove(function(e){
       left = e.pageX - 40;
       top = e.pageY - 60;
    
    });
    

    HTML

    <div id="map"></div>
    <div id="x"></div>
    <div id="y"></div>
    <div id="customTip" class="jvectormap-tip"></div>
    

    CSS

    #map {
        width: 500px;
        height: 400px;
    }