John
John

Reputation: 3115

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() {...}

Upvotes: 3

Views: 150

Answers (1)

Robert Longson
Robert Longson

Reputation: 124249

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

Upvotes: 2

Related Questions