1

Anyone know how to add css background without replacing the previous background with js?

for example,

<div style = "background: url (image.png)"> </ div>

after added

<div style = "background: url (image2.png), url (image.png)"> </ div>
3
  • Do you want to override the previous image with new one? Commented Feb 11, 2015 at 6:42
  • You cant have two backgrounds at once. Commented Feb 11, 2015 at 6:46
  • @JosanIracheta You can, with CSS3. Commented Feb 11, 2015 at 9:57

3 Answers 3

2

You can make use of CSS classes and switch between classes when required.

.class_one {
    background: url (image.png);
}

.class_two {
    background: url (image2.png), url (image.png);
}
Sign up to request clarification or add additional context in comments.

3 Comments

I need a background "image2.png" that can be changed with javascript
@Alan, is there any issues with the above solution?
May be @Gael's answer is you are looking for.
0

Here is the Javascript solution:

var backgroundStyle = document.querySelector("#container").style.background;

document.querySelector("#container").style.background = backgroundStyle + ", url('http://res.cloudinary.com/demo/image/upload/sample.jpg')";
<div style = "background: url('http://www.brightlinkprep.com/wp-content/uploads/2014/04/sample.jpg')" id="container" >
</div>

You can verify it using the Developer Tools / FireBug.

1 Comment

@Alan Note that the URL should be in quotes in your style.
0

Just get the background value, and append another url(img_url)

var my_div= document.querySelector("my_div");
if( my_div.style.background == "" )
 my_div.style.background= "url(image.png)";
else
 my_div.style.background+= ",url(image2.png)";

https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_multiple_backgrounds

3 Comments

is there a way to add, without get previous background?
You should have to test is already a background, to know if you need to add a comma.
I would suggest you to use classes as on the first answer. It's cleaner.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.