jquery dynamically change svg image xlink:href jquery dynamically change svg image xlink:href jquery jquery

jquery dynamically change svg image xlink:href


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", "http://blob.apliiq.com/sitestorage/fabric/" + randomNumber + ".png");    $('a#cta').attr("href", "/designyourown/?fabricID=" + randomNumber);});

JSFiddle Link: http://jsfiddle.net/arpitworld/jhetx/


I was trying to do this in JavaScript (without JQuery), but it was not working. For anyone who stumbles upon this in my situation, the trick was to call the setAttributeNS method and specify the xlink namespace for the href attribute. For example:

document.getElementById('background').setAttributeNS(    'http://www.w3.org/1999/xlink',     'xlink:href',     '<URL goes here>');


after hours of massaging I finally got it to work by keeping the url("") out of the xlink:href="" ugh!

$(document).ready(function() {            var randomNumber = Math.floor((Math.random()*855)+48);                $('#background').attr('xlink:href',"http://blob.apliiq.com/sitestorage/cropped-fabrics/" + randomNumber + "_573_465.jpg");                      });