Jump to content

[SOLVED] How can I change css properties with js?


landysaccount

Recommended Posts

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>

 

How can this be done?

 

Thanks in advanced for your help.

 

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

 

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

 

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?

function changePic(){

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

}

 

you were just writing the string pic inside the url instead of concatenating the value of the pic variable.

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.