Add information to a map in SVG

Asked

Viewed 140 times

0

I have a SVG map on my website. I would like to add a div for when the user hovers the mouse over a respective state, it shows the name of it. What happens is that if I include any information within <svg> styles are lost. It can be a div or span above the <a>.

Map I used

My code:

http://jsfiddle.net/felipestoker/g0c64uxw/

I put in Jsfiddle because the code exceeds the limit of snipset characters.

1 answer

1

You can select SVG elements normally, as if they were HTML.

I created an example from your example, where it prints in a <h3> the attribute xlink:href of each state. Jsfiddle

I put a class estado-svg in every state and put a Handler of the event mouseenter.

var estados = $(".estado-svg"), // seciona todos o <a> 
    teste = $("#teste"); // seleciona o <h3> para printar os estados

/*
poderia ser usado assim:

$(".estado-svg").on("mouseenter", function(){ ... });

Mas usei delegação de eventos por questões de performance
*/

$("#svg-map").on("mouseenter", ".estado-svg", function(){
    teste.html($(this).attr('xlink:href')); // Printa no <h3> o attributo xlink:href
});

From this example you can already get an idea of how to interact with the elements and use some library.


EDIT

That question of Stackoverflow in English answers your question.

  • Thank you for the explanation. What happens is that when I create a div within this SVG, it loses all formatting, even if I correctly inform the CSS structure. I would have to enter the state name within the svg.

  • the fact is that there is no element <div> in SVG, making your SVG invalid. That must be why it breaks the style. Look at the reference and find an element that serves as <div> for you.

  • I think you should take a look at the element <title> here

  • I edited the answer take a look there that I think solves your problem.

  • 1

    An example that I found in this link that I edited.

  • thanks for the links. About the code you put in, should I keep H3 in the same place? or should I use another HTML?

  • I just sent you an example of how to access SVG by javascript... You don’t need to use H3 if you don’t want to

  • Ah blz. But this example differs somewhat from what I have already done. Still, thank you. I would like to take advantage of what I already have.

Show 3 more comments

Browser other questions tagged

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