Nate McConnell Nate McConnell - 1 year ago 166
jQuery Question

jquery dynamically change svg image xlink:href

I'm trying to dynamically change the polygon's fill with an image not a fill color. To do so, I found a way to change the fill to an image, but I'm unable to dynamically change the xlink:href URL to a random url.
Any thoughts? Thanks for your help!

<svg xmlns="" xmlns:xlink="" version="1.1" x="0px" y="0px" width="320px" height="480px" viewBox="0 0 320 480" enable-background="new 0 0 320 480" xml:space="preserve" xmlns:xml="">
<pattern patternUnits="userSpaceOnUse" id="pat1" x="10" y="10"
width="425" height="319">
<image id="background" width="100%" height="100%"
xlink:href="" />
<g id="Layer_1">
<polygon class="background" fill="url(#pat1)" points="265.188,329.922 160.198,358 55.208,329.922 55.208,120.868 265.188,120.868 "/>

<g id="Layer_2">
<g id="brand_mark_1_">
<rect x="265.188" y="120.868" fill="#FFFFFF" width="23.812" height="44.378"/>
<path fill="#020304" d="M275.372,149.035c0,0.949,0.77,1.72,1.721,1.72c0.949,0,1.72-0.771,1.72-1.72 c0-0.023-0.003-0.044-0.004-0.066v-16.261c0.004-0.043,0.007-0.088,0.007-0.134c0-0.95-0.77-1.72-1.719-1.72 c-0.942,0-1.707,0.757-1.72,1.695h-0.005v16.461h0.001C275.374,149.017,275.372,149.025,275.372,149.035z"/>
<circle fill="#F5170D" cx="277.093" cy="153.541" r="1.72"/>

$(document).ready(function() {
var randomColor = Math.floor(Math.random()*16777215).toString(16),
randomNumber = Math.floor((Math.random()*855)+48),
backg = $('#background');
$("body").css("background-color", randomColor);
backg.attr("", "xlink:href","url(" + randomNumber + ".png)");
$('a#cta').attr("href", "/designyourown/?fabricID=" + randomNumber );

Answer Source

Works fine if you rectify the backg.attr function attributes.

$(document).ready(function () {
    var randomColor = Math.floor(Math.random() * 16777215).toString(16),
        randomNumber = Math.floor((Math.random() * 855) + 48),
        backg = $('#background');
    $("body").css("background-color", '#' + randomColor);
    backg.attr("xlink:href", "" + randomNumber + ".png");
    $('a#cta').attr("href", "/designyourown/?fabricID=" + randomNumber);

JSFiddle Link:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download