Hi all,
I’m new to JavaScript, so apologies if my question seems elementary. I’m trying to write a JS function that generates and sets a random y-coordinate for a background image that I set in a CSS stylesheet.
This is my HTML (I’m just quoting the relevant parts):
<body>
<div id="container_main">
<....sibling element...>
<div id="side_bar">
<a href="url of another page in site">
<span class="side_bar_box"></span>
</a>
</div>
<...sibling element...>
</div>
</body>
This is the relevant CSS rule:
span.side_bar_box {
position:absolute;
top:0;
left:0;
width:146px;
height:2250px;
background:url("my_image.jpg") 0 0 no-repeat;
}
The background image which I set for the empty <span> element is 7050px high, i.e it is much bigger than the box I created for it. So, I want to randomise the y-coordinate (between 0 and 4800px and in increments of 150px) with JS so that a different part of the image is visible with each page load.
I’ve managed to write the random coordinate generator:
function sbRandomiser(){
var imgOffset = Math.round(Math.random()*32)*150;
alert(imgOffset);
}
window.onload = sbRandomiser;
So far so good. The “alert” message confirms that the code works to generate a random number in multiples of 150 and smaller than 4800 which I can use to offset the y-coordinate of my background image.
Where I’m stumped is how to actually write this into my CSS rule (overwriting the default that’s defined in the stylesheet). For starters, I’m not sure whether I need to include the entire node tree in my selecter code, like so:
function sbRandomiser(){
var imgOffset= Math.round(Math.random()*32)*150;
var sbBox = document.getElementById("container_main").getElementById("side_bar").getElementsByTagName("<a>").getElementsByTagName("<span>");
sbBox.style.backgroundPosition = "0 -" + imgOffset + "px");
}
window.onload = sbRandomiser;
Or whether I can just home in straight on my <span> element like so:
function sbRandomiser(){
var imgOffset = Math.round(Math.random()*32)*150;
var sbBox = document.getElementsByName("side_bar_box");
sbBox.style.backgroundPosition = "0 -" + imgOffset + "px";
}
window.onload = sbRandomiser;
Both methods give me errors in FF: In the first case “getElementById is not a function” and in the second case “sbBox.style is undefined”.
Any help will be greatly appreciated!
Art