Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

attach events to SVG paths

Tags:

I have a SVG map in my html with the <svg> tag. and I want to attach events so I can click them and trigger some events. I know I can attach click event using jQuery on polygon elements. But some areas in this map are made using paths and I'd like to trigger some events when I click inside the paths, not on the paths.

What's the way to do that? Using jQuery is preferred.

like image 728
Gnijuohz Avatar asked Jul 28 '12 13:07

Gnijuohz


People also ask

Can you add onclick to SVG?

The onclick attribute specifies some script to run when the element is clicked. You can use this attribute with the following SVG elements: <a> <altGlyph>

How do I make a SVG image clickable?

The simplest way to make a portion of an SVG clickable is to add an SVG hyperlink element to the markup. This is as easy as wrapping the target with an <a> tag, just as you would a nested html element. Your <a> tag can surround a simple shape or more complex paths. It can surround a group of SVG elements or just one.

Can I add class to SVG path?

Just the same as you would add a class to an html element, by adding a class attribute. Though to be able to target that with css the svg code must be inserted into the document in-line, it can't be referenced by an <img> tag for example.

How does SVG path work?

It is often placed at the end of a path node, although not always. There is no difference between the uppercase and lowercase command. The path will move to point ( 10 , 10 ) and then move horizontally 80 points to the right, then 80 points down, then 80 points to the left, and then back to the start.


1 Answers

If you fill a <path> then clicking inside it (on the fill) will trigger the event handler:

Demo: http://jsfiddle.net/TmsrP/1/

<path id="sauce" fill="#f00" … />     
$('#sauce').on('click',function(){ … }); 

You can choose to explicitly fill the path with the color transparent and mouse events will still be caught:

Demo: http://jsfiddle.net/TmsrP/2/

<path fill="transparent" … /> 
like image 109
Phrogz Avatar answered Oct 15 '22 19:10

Phrogz