You can do this with the following script (read the comments)
var tooltip = document.querySelector('.map-tooltip');
// iterate through all `path` tags
[].forEach.call(document.querySelectorAll('path.HI-map'), function(item) {
// attach click event, you can read the URL from a attribute for example.
item.addEventListener('click', function(){
window.open('http://google.co.il')
});
// attach mouseenter event
item.addEventListener('mouseenter', function() {
var sel = this,
// get the borders of the path - see this question: http://stackoverflow.com/q/10643426/863110
pos = sel.getBoundingClientRect()
tooltip.style.display = 'block';
tooltip.style.top = pos.top + 'px';
tooltip.style.left = pos.left + 'px';
});
// when mouse leave hide the tooltip
item.addEventListener('mouseleave', function(){
tooltip.style.display = 'none';
});
});
See the updated jsfiddle: https://jsfiddle.net/3ojet4oL/3/
Update
- For dynamic tooltip text, there are some ways. One of them is to store the text on
data-*
attribute. In my example data-tooltip
, then you can read it when you want to show the tooltip:
html
<path class="HI-map maui" data-tooltip="tooltip10"
javascript
tooltip.innerText = item.getAttribute('data-tooltip');
Just now, I saw that you want to put an html in the tooltip. So I change a little bit the logic as you can see in the jsfiddle below. The logic is to store the tooltip content in object then, get it by the data-tooltip
attribute.
- For tooltip will move with the cursor, you just need to use
mousemove
event:
item.addEventListener('mousemove', function(e) {
tooltip.style.top = e.clientY + 'px';
tooltip.style.left = e.clientX + 'px';
});
https://jsfiddle.net/3ojet4oL/7/
Update 2
For dynamic URL add attribute data-link
the script will open this URL in new window.
https://jsfiddle.net/3ojet4oL/9/