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







Buttons with Images

Question: Can I create "pressable" buttons with images?

Answer: Yes. For each button, you'll need two images: one for the "pressed button" and the other for the "released button". Try the following example: point at any of the buttons below and press the left mouse button - the button image will change to "pressed" state. To watch the button images change back to "released" state, move the (pressed) mouse off the image and then release the mouse button.

Index Home

In this example, the "pressed button" images are btn1down.gif and btn2down.gif; the "released button" images are btn1up.gif and btn2up.gif. In order to make the buttons "pressable", each <IMG> tag is embedded in a hyperlink that has onMouseDown, onMouseUp, onMouseOut and onClick event handlers:

<a href="indexpg.htm"
onMouseDown="pressButton('btn1');return true;" 
onMouseUp="releaseButton('btn1');return true;" 
onMouseOut="releaseButton('btn1');return true;" 
onClick="return true;"
><img name=btn1 width=60 height=22 border=0 
alt="Index"
src="btn1up.gif"
></a>

<a href="startpag.htm"
onMouseDown="pressButton('btn2');return true;" 
onMouseUp="releaseButton('btn2');return true;" 
onMouseOut="releaseButton('btn2');return true;" 
onClick="return true;"
><img name=btn2 width=60 height=22 border=0 
alt="Home"
src="btn2up.gif"
></a>
The <HEAD> section of the page contains JavaScript code that preloads the image files and defines the event handler functions:
<script language="JavaScript">
<!--
// PRELOADING IMAGES
if (document.images) {
 btn1_down=new Image(); btn1_down.src="btn1down.gif"; 
 btn1_up  =new Image(); btn1_up.src  ="btn1up.gif"; 

 btn2_down=new Image(); btn2_down.src="btn2down.gif"; 
 btn2_up  =new Image(); btn2_up.src  ="btn2up.gif"; 
}

// EVENT HANDLERS
function pressButton(btName) {
 if (document.images)
  eval('document.'+btName+'.src='+btName+'_down.src');
}

function releaseButton(btName) {
 if (document.images)
  eval('document.'+btName+'.src='+btName+'_up.src');
}
//-->
</script>

BackBack