Home > other >  No event is working on loaded svg path though it works on svg previously loaded
No event is working on loaded svg path though it works on svg previously loaded

Time:03-16

I'm trying to use click event on path on loaded svg element. But it is not working on loaded svg. However, it works perfectly if the svg is not loaded.

This code works perfectly.

<div >
  <?php       
      echo file_get_contents('a.svg'); 
  ?> 
</div>

$(document).ready(function () {
    $("path").click(function () {

        alert("clicked");
    });

});

But when trying to load the svg using jquery,it does not work. Can anyone explain why this is happening?

$(document).ready(function () {

$("#addImage").click(function () {
    $("#fileinput").click();
});

$("#fileinput").change(function () {
    if (this.files && this.files[0]) {
        let reader = new FileReader();
        reader.onload = imageIsLoaded;
        reader.readAsDataURL(this.files[0]);
    }
});

function imageIsLoaded(e) {
    $(".mapdiv").load(e.target.result);
}


$("path").click(function () {
    alert("clicked");
    });
})

CodePudding user response:

To be sure that the content has been appended to the DOM you need to wait for the .load(). You can do that as a call back function. Read mere here: .load() | jQuery API Documentation. OR use the .live().

$(document).ready(function() {
  $("#addImage").click(function() {
    $("#fileinput").click();
  });

  $("#fileinput").change(function() {
    if (this.files && this.files[0]) {
      let reader = new FileReader();
      reader.onload = imageIsLoaded;
      reader.readAsDataURL(this.files[0]);
    }
  });
});

function imageIsLoaded(e) {
  $(".mapdiv").load(e.target.result, function() {
    $("path").click(function() {
      alert("clicked");
    });
  });
});
  • Related