/    Sign up×
Community /Pin to ProfileBookmark

How can I change css properties with js?

Hello.

I would like to know how can I use javascript to change a css property in a file. For example:

I have a css file named styles with:
#HEADER { height:130px; background-image: url(p142.jpg); background-repeat: no-repeat; background-color: #CCCCCC; border-top: 3px solid Black; }

I would like the bg image to change randomly by calling a js function. I don’t know how to do it since css and js are in different files.

I have this in the index.php page:

<script language=”JavaScript”>

function getPic(){
var pic = new Array();
pic[0] = “./images/temp.jpg”;
pic[1] = “./images/p128.jpg”;
pic[2] = “./images/p129.jpg”;
pic[3] = “./images/p130.jpg”;
pic[4] = “./images/p131.jpg”;
pic[5] = “./images/p132.jpg”;
pic[6] = “./images/p133.jpg”;
pic[7] = “./images/p134.jpg”;
pic[8] = “./images/p135.jpg”;
pic[9] = “./images/p136.jpg”;
pic[10] = “./images/p137.jpg”;
pic[11] = “./images/p138.jpg”;
pic[12] = “./images/p139.jpg”;
pic[13] = “./images/p140.jpg”;
pic[14] = “./images/p141.jpg”;
pic[15] = “./images/p142.jpg”;

rdm = Math.floor( Math.random() * pic.length );

return pic[ rdm ];

} // end getPic function

….
….
….
….

<div id=”HEADER”></div>

I’m trying this technique but, is not working:

function changePic(){

var pic = getPic();
document.getElementById(“Visual”).style.background = “url( pic )”;
return true;

}// end function changePic
///////////////////////////////////

But, if I do this it works:
document.getElementById(“Visual”).style.background = “url( ./images/p130.jpg )”;

I’m getting the same value with variable pic, tested using window.alert(pic), but somehow it does not like it and is not changing the pic.

Any ideas?

Thanks in advanced for your help.

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@gil_davisSep 17.2009 — If "pic" is a var, thendocument.getElementById("Visual").style.background = "url(" + pic + ")";ought to work.
Copy linkTweet thisAlerts:
@landysaccountauthorSep 17.2009 — That did work. Thanks a million.
×

Success!

Help @landysaccount spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.29,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...