Reputation: 441
I want to create predefined button that has linear gradient as background image, but in the page itself, when I creating the buttons (via JS) I want to dynamically add the picture on the button as background.
Normally, if I would add image for every button in CSS like the following:
button{
width:96px; height:96px; border-radius:50%;
background:radial-gradient(48px 48px,rgba(0,0,255,0),rgba(0,0,255,0) 60%, #00f 70%),url('OK.png');
}
It will work - but if I need to go this way, I will need to create custom classes for every image, and this is not convenient for me and not that dynamic as I want. By leaving the CSS as the template I want:
button{
width:96px; height:96px; border-radius:50%;
background:radial-gradient(48px 48px,rgba(0,0,255,0),rgba(0,0,255,0) 60%, #00f 70%);
}
In JS if I want to add image dynamically to
ButtonOK.style.backGroundImage="OK.png";
It will overwrite the gradient (obvious). I cannot "copy" the CSS code into JS, because I want to leave it there (in a case one of my users will change the gradient color in the css - my JS file need to be prepared for this change.
I cound do:
styleSheets[0].cssRules[ToFindTheRuleIndex].style.backgroundImage+",url('"+GivenImage+"');"
However, this way I need to assume the user specified in CSS the background image property AND that the stylesheet is used is the only default one in 0, OR even if other custom CSS files, the default one is still the first. Need to make the JS function too long and too complicated......
The question:
How can I add the image in JS on top of the linear gradient so it will be like in my first example?
Pure JS solution is requested.
Thanks a lot:)
Upvotes: 0
Views: 139
Reputation: 21672
If you were open to using background-image
instead of background
(which should work the same), you can use a regex replace to remove the existing image URL and replace it with a new one.
The method below uses getComputedStyle
so that it pulls the background from your CSS, only replacing the image at the end.
function replaceBackgroundImage(element, newImage) {
var bg = getComputedStyle(element).getPropertyValue("background-image");
bg = `${bg.replace(/, url\((.*)\)/g, '')}, url('${newImage}')`;
element.style.backgroundImage = bg;
}
var ButtonOK = document.getElementById("ok");
replaceBackgroundImage(ButtonOK, "MyNewImage.png");
console.log(ButtonOK.style.backgroundImage);
replaceBackgroundImage(ButtonOK, "AnotherImage.png");
console.log(ButtonOK.style.backgroundImage);
#ok {
padding: 40px;
background-image: radial-gradient(48px 48px, rgba(0, 0, 255, 0), rgba(0, 0, 255, 0) 60%, #00f 70%);
}
<button id="ok">OK</button>
Upvotes: 1