Click event on an SVG

Asked

Viewed 360 times

3

I have a map of Brazil, in an SVG, where I would like to present a div next to each state when clicking on it.

I managed to work the color change with hover using the ID of each state of Brazil:

function highlight_map_states(){
  if($(".states_section").length>0){
     $(".states_section .list_states .item .link").hover(function(){
       var a="#state_"+$(this).text().toLowerCase();
       $(a).attr("class","state hover")
     },function(){
       var a="#state_"+$(this).text().toLowerCase();
       $(a).attr("class","state")
     })
  }
};

How do I have one click on each state to make one appear div?

Note: You can’t put all the code here because the question has a maximum character size, but it gets a demo on Codepen.

1 answer

2


What you’re looking for is the method getBoundingClientRect() that will return you an object ClientRect with the distance in pixels to top, right, bottom and left.

The method Element.getBoundingClientRect() returns the size of an element and its position relative to the display window.

The amount returned is of the type float, but you can make use of it directly in the CSS properties for the element to position.


Example hover

Example of the mouse going over a path, where a <div/> next to it:

var $toolTip = $('.tooltip');

$('path').hover(function(){

    var t = this.getBoundingClientRect().top,   // distancia do topo
        l = this.getBoundingClientRect().left;  // distancia da esquerda

    $toolTip .css({
        "top": t + "px",
        "left": l + "px"
    }).show();
    
}, function(){
    $toolTip.hide();
});

See full demo on Jsfiddle.


Example click

Example of clicking on a path or circle appearing to <div/> next to the clicked element:

// Faz aparecer elemento junto da path ou circle que recebeu o clique
$('path, circle').click(function(e){
    e.preventDefault();

    var t = this.getBoundingClientRect().top,
        l = this.getBoundingClientRect().left;

    $tooltip.css({
        "top": t + "px"
        "left": l + "px"
    }).show();
});

// Desabilita clique nas descrições e textos
$('desc, text').click(function(e){
    e.preventDefault();
});

See full demo on Jsfiddle.


I cannot put together a demonstration here because the maximum number of characters in the answer is 30000.

  • Got it Zuul!! And how do I create a different div for each state?? Excuse the ignorance rs because I don’t know any javascript! Thank you very much ;)

  • @I don’t know what you want them for div nor what will be inside each one to advise you in the best way. But it would not be more practical and simple to have the div in HTML, such as the examples in the answer, and when using them, call the .show() to present them ? Anyway, there are two examples in Jsfiddle for: Create DIV with Javascript and create DIV with jQuery.

  • Thank you very much Zuul!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.