About This Product
FontsMadeEasy.com
 
Search This Database:
| Over 5000 Free Fonts | Tutorials | Javascript Forum | Other Javascript Resources | Cheat Sheet
Tutorial archive
General Questions
Javascript 1.2
Navigation
Numbers
Strings
Object Model
Reference Manual
Dialog
Windows
Frames
Forms
Images
Mouse Events
Colors
File Access
Control Status Bar
Dates and Time
Cookies
Client Information
Bookmarklets


OnMouseDown Effects

Question: How do I change an image when the user clicks on it?

Answer: This is very similar to onMouseOver effects. However, the techniques described on this page will work only in Netscape 4.x or Internet Explorer 4.x (or newer browsers) because versions 3.x of both browsers do not support the onMouseDown and onMouseUp event handlers.

Here is a simple example: This image changes when you point at it!
Press the mouse button while pointing at this folder, and it will open. Release the mouse button, and the folder will close.

The <IMG> tag in this example is embedded in a hyperlink that has onMouseDown, onMouseUp and onMouseOut event handlers:

<a href="#"
onMouseDown="handlePress();return true;" 
onMouseUp="handleRelease();return true;" 
onMouseOut="handleRelease();return true;" 
onClick="return false;"
><img name=imgName width=17 height=15 border=0 
alt="This image changes when you point at it!"
src="../hi-icons/2.gif"
></a>
In the <HEAD> section of the page, we have JavaScript code that preloads the image files and defines the event handler functions:
<script language="JavaScript">
<!--
// PRELOADING IMAGES
if (document.images) {
 img_on =new Image();  img_on.src ="../hi-icons/1.gif"; 
 img_off=new Image();  img_off.src="../hi-icons/2.gif"; 
}

function handlePress() { 
 if (document.images) document.imgName.src=img_on.src;
}

function handleRelease() {
 if (document.images) document.imgName.src=img_off.src;
}

//-->
</script>

Here is a more complex example with several images: This image changes when you point at it! This image changes when you point at it! This image changes when you point at it! This image changes when you point at it! This image changes when you point at it! This image changes when you point at it!
The code is very similar to the above, except that now the event handler functions take the image's number as a parameter. (To see the actual code, view the source of this page.)

BackBack