Click here to Skip to main content
15,878,543 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a SVG which has some linearGradient elements which changes at button click Everything works fine as you can see here: Edit fiddle - JSFiddle[^]

My questions is how could do the same thing if the svg from my example is an external file and is called in an <object> tag?

What I have tried:

My svg image:
HTML
<object data="Img/PumpStation/Pump.svg" type="image/svg+xml" id="alphasvg1111"></object>

My button:
ASP.NET
<asp:Button ID="Button1" class="test" runat="server" Text="Button" />

My jQuery function:
JavaScript
jQuery('.test').on('click', function () {
    //$("object").contents().find("path").attr({ "fill": "red" });
    jQuery('object stop').each(function () {
        var color = jQuery(this).css('stop-color');
        if (color === 'rgb(77, 77, 77)') {
            jQuery(this).css('stop-color', '#ff0000');
        }
    });
});

If I use:
JavaScript
$("object").contents().find("path").attr({ "fill": "red" });
, my SVG turns red when button is clicked. Why the rest of the function is not working?
Posted
Updated 23-Feb-23 16:30pm
v3

1 solution

The <object> element creates a separate document, in a similar way to an <iframe>.

Since it's from the same domain, you can get access to that document using jQuery's contents method[^]. But a jQuery selector run against the top-level document will not be able to select elements in the nested document.

jQuery("object stop") will return zero matches, since the stop is not part of the current document. But jQuery("object").contents().find("stop") should work.
JavaScript
jQuery('.test').on('click', function () {
    jQuery('object').contents().find('stop').each(function () {
        var color = jQuery(this).css('stop-color');
        if (color === 'rgb(77, 77, 77)') {
            jQuery(this).css('stop-color', '#ff0000');
        }
    });
});
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900