Icewine
Icewine

Reputation: 1851

How to change SVG pattern image dynamically with javascript on hyperlink click

I have looked and not found a suitable answer for this. I have found answers for changing fill color but not the pattern images.

Fiddle

JAVASCRIPT

$("a#changePattern").click(function(){
var value = $('#pattern');           
value.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', 'http://3.bp.blogspot.com/-zX0zs-7rHOM/UJ2halaWKlI/AAAAAAAACXg/2rape7g5Y6c/s320/tiling7small.jpg');
});

HTML

<a href='#' id='changePattern'>change pattern</a>
<svg version="1.1" id="&#x30EC;&#x30A4;&#x30E4;&#x30FC;_1"
 xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="105.513px"
 height="80.789px" viewBox="0 0 105.513 80.789" style="enable-background:new 0 0 105.513 80.789;" xml:space="preserve">
 <defs>
    <pattern id='pattern' patternUnits='userSpaceOnUse' width='10' height='10'>
        <image xlink:href='http://3.bp.blogspot.com/--4FM7pgC20Q/UKSCRo5QaII/AAAAAAAACa8/uh8wEsX7naM/s1600/new-tiling-1.jpeg' x='0'y='0'width='10px'height='10px' />
    </pattern>
</defs>
 <polygon style="fill:url(#pattern); stroke:#060001;stroke-width:0.15;" points="64.392,52.845  0.878,79.872 23.175,20.413 104.256,0.818 "/>
 </svg>

I need to be able to change multiple patterns in a svg image without reloading the page.

Is this possible?

Upvotes: 1

Views: 2150

Answers (1)

GavinoGrifoni
GavinoGrifoni

Reputation: 763

You can do this with jQuery (which I think you were already trying to use but did not import it in jsFiddle):

Link to fiddle

Js code

$("#changePattern").click(function(){
var value = $('#pattern image'); // select 'image' tag inside element with id 'pattern'          
value.attr('xlink:href', 'http://3.bp.blogspot.com/-zX0zs-7rHOM/UJ2halaWKlI/AAAAAAAACXg/2rape7g5Y6c/s320/tiling7small.jpg');
});

Upvotes: 3

Related Questions