0

I have to change the background of a div using JavaScript. I have managed to do that, using document.getElementById('test').style.background = "url('img/test.jpg')";

Now, how do i change other properties like repeat, scroll,etc?

The css i want for the test is like

background: #f00 url('img/test.jpg') no-repeat fixed 10px 10px;

I cannot use jQuery, since I do not want to include the library for only a small thing.

7 Answers 7

4

Instead of setting all the css properties with javascript. I would suggest to create an additional css rule for this element with certain class. And then use javascript to add or remove this class from this element when you need it.

Eg.

function changeBG(){
  var element = document.getElementById('test');
  element.setAttribute("class", 'newBG'); //For Most Browsers
  element.setAttribute("className", 'newBG'); //For IE; harmless to other browsers.
}
Sign up to request clarification or add additional context in comments.

Comments

2

Below should work:

document.getElementById('test').style.background = "#f00 url('img/test.jpg') no-repeat fixed 10px 10px"

Or you can use individual properties such as backgroundColor of style object. See here for various properties of style object.

Comments

1

Make a class with those properties, and then just assign/remove that class through javascript.

Comments

1
function displayResult()
{
document.body.style.background="#f3f3f3 url('img_tree.png') no-repeat right top";
}

See following:
http://www.w3schools.com/jsref/prop_style_background.asp

Comments

0

As everyone suggests I also prefer using a class, but if you insist you can use JS for this as you use CSS

document.getElementById('test').style.background = "url('img/test.jpg') no-repeat fixed";

Comments

0

Use next style properties for changing background:

document.getElementById('test').style.background
document.getElementById('test').style.backgroundAttachment
document.getElementById('test').style.backgroundClip
document.getElementById('test').style.backgroundColor
document.getElementById('test').style.backgroundImage
document.getElementById('test').style.backgroundOrigin
document.getElementById('test').style.backgroundPosition
document.getElementById('test').style.backgroundPositionX
document.getElementById('test').style.backgroundPositionY
document.getElementById('test').style.backgroundRepeat
document.getElementById('test').style.backgroundSize

http://msdn.microsoft.com/en-us/library/ms535240%28v=vs.85%29.aspx

Comments

-1

This will give the class to the dom element

document.getElementById('test').className = 'cssName'

Comments

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.