Change Background Using Javascript
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
Solution 1:
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.
functionchangeBG(){
var element = document.getElementById('test');
element.setAttribute("class", 'newBG'); //For Most Browsers
element.setAttribute("className", 'newBG'); //For IE; harmless to other browsers.
}
Solution 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.
Solution 3:
Make a class with those properties, and then just assign/remove that class through javascript.
Solution 4:
functiondisplayResult()
{
document.body.style.background="#f3f3f3 url('img_tree.png') no-repeat right top";
}
See following: http://www.w3schools.com/jsref/prop_style_background.asp
Solution 5:
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
";
Post a Comment for "Change Background Using Javascript"