Add onclick to svg path by id

Using this Stackoverflow Question and first answer, I was able to convert the SVG image into an embedded svg into a finished document. I can also reference its path elements from CSS to add a hover stroke.

The next thing I'm trying to accomplish is to add onclick to each path without adding it to the svg file itself. I suggested that since CSS can identify every class of a path, I should also be able to identify every path identifier in javascript, but I find it hard to figure out how to do this. Here is my code:

<body> <div id="mapSideBar" class="left"> </div> <div id="mapMain" class="left"> <img id = "mapImg" src="canada2.svg" class="logo" /> </div> </body> 

I have a function mentioned in the link above to convert it to an embedded SVG, and my paths have identifiers - path1, path2, path3 and path4. I tried adding the following to the jQuery(document).ready() function:

 var $paths = jQuery(document).find('path'); $paths.each(function() { (this).click(onImgClick((this).id)); }); 

to see if I can get a handle on every path, and I can't. Is there something I am missing, or is there a way to assign onclick event handlers for each path?

Thank you rishi

+5
source share
2 answers

Here is a working solution: JSFiddle

HTML :

 <img class="svg" src="http://upload.wikimedia.org/wikipedia/en/e/e5/My_Little_Pony_Friendship_is_Magic_logo.svg"/> 

CSS :

 svg path:hover { fill: red !important; } 

JavaScript :

 /* * Replace all SVG images with inline SVG */ jQuery('img.svg').each(function(){ var $img = jQuery(this); var imgID = $img.attr('id'); var imgClass = $img.attr('class'); var imgURL = $img.attr('src'); jQuery.get(imgURL, function(data) { // Get the SVG tag, ignore the rest var $svg = jQuery(data).find('svg'); // Add replaced image ID to the new SVG if(typeof imgID !== 'undefined') { $svg = $svg.attr('id', imgID); } // Add replaced image classes to the new SVG if(typeof imgClass !== 'undefined') { $svg = $svg.attr('class', imgClass+' replaced-svg'); } // Remove any invalid XML tags as per http://validator.w3.org $svg = $svg.removeAttr('xmlns:a'); // Replace image with new SVG $img.replaceWith($svg); // Add an handler jQuery('path').each(function() { jQuery(this).click(function() {alert(jQuery(this).attr('id'));}); }); }); }); 
+6
source

jQuery(document).ready() not enough to make sure your built-in svg has loaded correctly.

To check if this problem is relevant, add a timeout to your function and see if it works better.

In the end, you probably need to add a callback to the function that performs the svg inline conversion.

0
source

Source: https://habr.com/ru/post/1201184/


All Articles