- A continually scrollling background image using javascript
- A static overlay image with transparency
- Random starting positions for both images allowing for a unique appearance on every page load, again using javascript
The XHTML & CSS
Start off by downloading the latest copy of the jQuery core library. This will be the engine that powers our new element, but we will need a little more code to act as a steering wheel. We’ll come back to that later. Link the jquery and custom.js into your header in the usual way. Should you want to fix the ie5.5/6 transparency failing, you may also want to include a .png fix javascript file
< link rel=“stylesheet” type=“text/css” media=“screen” href=“css/style.css” /> |
< script type=“text/javascript” src=“js/jquery-1.3.2.min.js”></ script > |
< script type=“text/javascript” src=“js/custom.js”></ script > |
< script type=“text/javascript” src=“js/jquery.pngfix.js”></ script > |
DD_belatedPNG.fix(’.png-fix’); |
The xhtml is as straightforward as can be, using just two divs as outlined earlier. You can add any further content you want into the content of these divs. Adding content would also make the setup of the element semantically correct, not using empty divs, and using backgrounds as backgrounds! For illustrative purposes, this web design element example contains a further div with styled text within.
< span class = "red" >You can add further content on top of your design into these divs here.</ span > |
Apply the following CSS attributes to your two containing divs. Obviously you will need to set the width and height according to the images you have produced.
background : url (../images/gradient.jpg); |
background : url (../images/overlay.png); |
And finally, the javascript…
var backgroundheight = 2000; |
var backgroundheight_two = 1000; |
offset = Math.round(Math.floor(Math.random()* 2001)); |
offset2 = Math.round(Math.floor(Math.random()* 1001)); |
function scrollbackground() { |
offset = (offset < 1) ? offset + (backgroundheight – 1) : offset – 1; |
$(’ #container’).css(“background-position”, “50% “ + offset + “px”); |
$(’ #overlay’).css(“background-position”, “50% “ + offset2 + “px”);<br> |
The above is the contents of custom.js – you will need to modify this slightly to fit your own needs. Firstly, the height of your two images should be entered in to the two ‘backgroundheight’ variables (in pixels). The first being the coloured gradient to be animated and the second, the overlaid static image.
Secondly, take the height of these two images and add 1. Insert these numbers to create a randomised starting position for both images in place of ‘2001’ and ‘1001’ above.
You can change the scrolling speed by altering the value ‘100’, though it seems 100 is optimum and altering this may not produce an animation that is quite as smooth.
Finally change ‘#content‘ and ‘#overlay‘ to the IDs of your containing divs if you have decided to change them.
That’s it!