Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap

Q376 How do I make an image bounce off the edges of the browser?

You are here: irt.org | FAQ | DHTML | Q376 [ previous next ]

Try the following which works in Netscape Navigator 4 and Internet Explorer 4 (thanks to Don Binns for pointing out the body obejcts offsetWidth and offsetHeight properties in Internet Explorer 4):

<DIV ID="myid" STYLE="position:absolute;top:0;left:0;">
<img id=myimg src="littlepsycho.gif" Width="40"Height="40">

<SCRIPT LANGUAGE="JavaScript"><!--
var xInc=10, yInc=10;
if(document.all) var xMax = document.body.offsetWidth, yMax = document.body.offsetHeight;
else if (document.layers) var xMax = window.innerWidth - document.myid.document.images[0].width, yMax = window.innerHeight - document.myid.document.images[0].height;

function moveit() {
    if (document.all) {
        xNew = document.all('myid').style.posLeft + xInc;
        yNew = document.all('myid').style.posTop + yInc;
    else if (document.layers) {
        xNew = document.myid.left + xInc;
        yNew = document.myid.top + yInc;

    if (xNew < xMax && xNew >=0) {
        if (document.all) document.all('myid').style.posLeft = xNew;
        else if (document.layers) document.myid.left = xNew;
    else xInc = xInc * (-1);

    if (yNew < yMax && yNew>=0) {
        if (document.all) document.all('myid').style.posTop = yNew;
        else if (document.layers) document.myid.top = yNew;
    else yInc = yInc * (-1);

if (document.all || document.layers)

The following was submitted by Eliot:

In Internet Explorer you can use <marquee>sample.gif</marquee> and the image will scroll. Put <marqueebehavior>sample.gif</marqueebehavior> and the image will bounce back and forth, just as if it were text:


Feedback on 'Q376 How do I make an image bounce off the edges of the browser?'

©2018 Martin Webb