doggie brezy doggie brezy - 15 days ago 6
Javascript Question

How to retrieve svg file name or path from itself using javascript or jQuery

Please is there a possible way I can get the file name of an svg file directly from the file itself for example I have this folder and files

+mainFolder/ <!--Main Folder-->
+svgImgs/ <!--SVG image Folder-->
+image.svg <!--SVG image-->
+index.php <!--index page of Main Folder-->


Then in my index page I have this
ajax()
call that retrieves and appends the
image.svg
file.

$.get('svgImgs/image.svg', null, function(data){
var svgNode = $('svg', data);
var docNode = document.adoptNode(svgNode[0]);
$('div').append(docNode);
}, 'xml');


Now the issue is that I want to trigger an
onclick
event for the
svg
files as I have multiple of them. and I want to pass the svg file name or svg path as the parameter

<svg>
<script>
$('svg').on('load', function(){
fileName = //get the file name or file path
$(this).attr('onclick', 'myFunction('+fileName+')');
})
</script>
</svg>


So I can run the
myFunction()
in my index file

function myFunction(svg){
//functions here
}


Please any better suggestion on how I can do this?

Answer

You can wrap the $.get() call in another function and pass the filename as a parameter, which will then allow you to do this for multiple svg files easily...

function getSvg(filename) {
    $.get(filename, null, function(data) {
        var svgNode = $('svg', data);

        svgNode.on("click", function() {
            myFunction(filename);
        });

        var docNode = document.adoptNode(svgNode[0]);
        $('div').append(docNode);
    }, 'xml');
}

getSvg("svgImgs/image.svg");
// get other svg files...