Home Articles FAQs XREF Games Software Instant Books About Feedback Search Site-Map
irt.org logo

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

irt.org | Knowledge Base | DHTML | Q376 [ previous next ]

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

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">
</DIV>

<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);

    setTimeout("moveit()",75);
}
if (document.all || document.layers)
    moveit();
//--></SCRIPT>

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:

<marquee>sample.gif</marquee>
<marqueebehavior>sample.gif</marqueebehavior>

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


Provide feedback ...
AddThis Social Bookmark Button

Provide feedback ... AddThis Social Bookmark Button


Last Updated: 30th March 2008. Maintained by: Martin Webb
irt.org liability, trademark, document use, privacy statement and software licensing rules apply.
Copyright © 1996-2008 irt.org, All Rights Reserved.