doggie brezy
doggie brezy

Reputation: 297

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?

Upvotes: 2

Views: 1741

Answers (2)

KANAYO AUGUSTIN UG
KANAYO AUGUSTIN UG

Reputation: 2188

From what @Archer has written, this is a short and quick method. Instead of nesting your $.get() call in a function, you can just do this

$.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');

Then in myFunction() you just get the value passed

function myFunction(svg){
    console.log(svg);
}

Upvotes: 1

Reinstate Monica Cellio
Reinstate Monica Cellio

Reputation: 26143

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...

Upvotes: 1

Related Questions