Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing elements in SVG using JQuery

I have this:

<button type="button" id="btn" value="Release">Click Here!</button>     
...

<body>
<object data="books.svg" type="image/svg+xml" id="svg" width="1300" height="700"></object>
</body>

<script>
var a = document.getElementById("svg");
var svgDoc

a.addEventListener("load", function() {
     svgDoc = a.contentDocument;
}, false);

$(window).load(function() {
    console.log($(svgDoc).find("#book1").attr("fill"))
});

$(document).ready(function() {
    $("#btn").click(function() {
        console.log("You are here")
        $(svgDoc).find("#book1").attr("fill","#000000")
    })
})

$(window).load(function() { works, but

$(document).ready(function() {
        $("#btn").click(function() {

... doesn't. Why is that?

Edit: Added more code

Edit #2: Got it to work. Followed Robert Longson's suggestion and changed this:

$(document).ready(function() {....})

to this:

a.addEventListener("load", function() {...}, false);

JQuery:

$("#btn").on('click', function() {...}
like image 740
John Avatar asked Mar 16 '26 07:03

John


1 Answers

$(document).ready();

Will fire as soon as the web browser runs after the parser is done with the DOM for that page, but before all the embedded objects are initialised. This is useful if you want to execute JavaScript as soon as possible, but it's not what you want in your case. I imagine it is implemented off the DOMContentLoaded event as that matches the ready() description

You need the UA to have loaded the <object> contents in order to manipulate it. You can attach to the <object> element onload event or as you are doing to the page onload.

like image 129
Robert Longson Avatar answered Mar 17 '26 20:03

Robert Longson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!