1. Tech

Your suggestion is on its way!

An email with a link to:


was emailed to:

Thanks for sharing About.com with others!

This is a web page object.

Web Page Animation

4. Random Start Position

clr gif

In the last tutorial we looked at positioning a web page object at a specific spot on the screen and then having the object maintain that spot on the screen as we scrolled the web page. In this tutorial we will look at extending the processing that we have to randomly position the object on the screen when the page first displays. We will have the object maintain whatever random position is selected even when the page is scrolled.

In the prior tutorial we adjusted the position manually to allow for the width of our object. By testing the width and height of the object itself (again using functions that I have written for you) we can allow the object to be placed anywhere on the screen without it disappearing off of the screen.

To be able to select a random position at the start we need to wait until the page has loaded before selecting the position (so that we can work out the width and height of our object). To maintain that position we don't want to call all of the processing again so this time we'll set up two functions - one called start (that is called to assign the random position) and one called moveit (to display the object at that position). When the page is scrolled we call the moveit function to correct the position where the object is displayed.

var xxx = 0; var yyy = 0;
function start() {
var w = objWidth('myobj');
var h = objHeight('myobj');
xxx = Math.floor(Math.random()* (pageWidth()-w));
yyy = Math.floor(Math.random()* (pageHeight()-h));

function moveit() {
var x = (posLeft()+xxx) + 'px';
var y = (posTop()+yyy) + 'px';

window.onload = start;
window.onscroll = moveit;

We are now using the pageWidth and pageHeight functions that we already have in our animhead.js file directly rather than having them called from the posRight and posBottom functions. We subtract an appropriate value from this to allow for the actual size of our web page object and multiply this by a random number (which is always between 0 and 1) to randomly select a position on the screen. By adding the posTop and posLeft to this we take into account the current scroll position of the page so as to maintain our object in the same position on the screen as was initially randomly selected as our web page scrolls behind it.

The xxx and yyy variables are defined outside of both functions so that the random start position can be assigned in one function and used in the other.

See More About
Explore JavaScript
By Category
    javascriptJavaScriptcomputeTechb950eefb2a063b7b4e00399d305537ef3a00038e0c006b2ahttp://javascript.about.comod526F6F7412274terminatedStephen Chapmanjavascriptguide3Og00025zNIP11970-01-0110/od/index.htm0526F6F741approved/od
  1. About.com
  2. Tech
  3. JavaScript

©2015 About.com. All rights reserved.