Javascript within a Cascading Style Sheet (CSS)
I know I know - this isn't the usual subject matter for my blog. My blog is more about the Batman-vs-Kim Possible fan-fiction-type geek and less the slashdot-Linux-type geek. But I was searching for this information over the weekend and couldn't find anything, so I figure I'd blog it here and maybe someday someone will google the topic and save themselves some time. I used to do stuff like this at my old job, but it's been a while, so if I made any mistakes... well, I'm a writer, not a programmer.
The issue : I was trying to get a javascript to rotate background images. Most people suggest using PHP to rotate images, but the webserver that I was trying to put this page doesn't support PHP. I had to do it in javascript.
The tricky part - I needed the javascript to be inside the CSS, because certain properties like repeat-x and repeat-y are (as best as I can tell) only available through CSS. I did everything I could to get that javascript to activate inside the CSS, but it wouldn't do it.
The solution : Use javascript to create the CSS.
As you can see, the first part of the javascript creates the array with the various graphics. The second part of the javascript document.writes the style tag and defines the body properties.
Hope this helps someone out there who was googling for "help with javascript and CSS"... and not someone out there who was googling for "Batman-vs-Kim Possible fan fiction". If so, FOR SHAME.
The issue : I was trying to get a javascript to rotate background images. Most people suggest using PHP to rotate images, but the webserver that I was trying to put this page doesn't support PHP. I had to do it in javascript.
The tricky part - I needed the javascript to be inside the CSS, because certain properties like repeat-x and repeat-y are (as best as I can tell) only available through CSS. I did everything I could to get that javascript to activate inside the CSS, but it wouldn't do it.
The solution : Use javascript to create the CSS.
<SCRIPT LANGUAGE="JavaScript"><!--
function random_content(){
var mycontent=new Array()
mycontent[1]='01.jpg'
mycontent[2]='02.jpg'
mycontent[3]='03.jpg'
var ry=Math.floor(Math.random()*mycontent.length)
if (ry==0)
ry=1
document.write("<style type=\"text/css\"> body { margin: 0px; padding : 0; background : #CCCCCC url(" + mycontent[ry] + ") fixed repeat-y bottom left; } </style>")
}
random_content()
// --></SCRIPT>As you can see, the first part of the javascript creates the array with the various graphics. The second part of the javascript document.writes the style tag and defines the body properties.
Hope this helps someone out there who was googling for "help with javascript and CSS"... and not someone out there who was googling for "Batman-vs-Kim Possible fan fiction". If so, FOR SHAME.


0 Comments:
Post a Comment
<< Home