Currently, I am facing a challenge in dynamically updating the background-image
property of a div
while preserving other background-related properties (such as color and gradient) using jQuery's .css()
function. Although I can successfully replace the image, I lose the rest of the properties. Is there a way to achieve this without sacrificing the other CSS background attributes?
CSS
.myClass{
width:100px;
height:100px;
background:url(http://upload.wikimedia.org/wikipedia/commons/b/b9/Hookem_hand.gif) center no-repeat, repeating-linear-gradient(135deg, transparent, transparent 3px, rgb(102, 102, 102) 3px, rgb(102, 102, 102) 6px), linear-gradient(rgb(51, 51, 51), rgb(153, 153, 153));
color:white;
text-align:center;
}
JS/JQuery
var elem = $("#changeMe");
var pattern = new RegExp(/url\(https?:[^,]*\)/);
var background = elem.css("background");
var replacementImage = "url(http://upload.wikimedia.org/wikipedia/commons/d/d1/Circle-question.png)";
var match = background.match(pattern);
console.log(match);
var updatedBG = background.replace(pattern,replacementImage);
console.log(updatedBG);
// elem.css({"background-image":replacementImage}); //this removes the other backgroud css such as gradient and color
elem.css({"background":updatedBG}); //this does not have any effect on the div
HTML
<div class="myClass">
unchanged
</div>
<div id="changeMe" class="myClass">
changed
</div>
I have set up a JSFiddle to showcase the issue: http://jsfiddle.net/joedegiovanni/2ns61st9/4/
If you have any insights on how to properly handle this task without losing the other background properties, your assistance would be greatly appreciated.
Thank you for your anticipated help.