JavaScript Event Handlers – onmouseover() and onmouseout()

JavaScript Event Handlers – onmouseover() and onmouseout() cover image
  1. Home
  2. JavaScript
  3. JavaScript Event Handlers – onmouseover() and onmouseout()

More interactivity – making several things happen at the same time

To change both the background color and the status bar message when the mouse pointer is passed over a link, you have to include two JavaScript statements to the same event handler, onmouseover.

<A HREF="//www.webdevelopersnotes.com" 
onmouseover="window.status='Go Back To Home Page';
document.bgColor='#EEEEEE'">
Change the background color and put a message on the status bar
</A>

Note: The two JavaScript statements window.status=’Go Back To Home Page’ and document.bgColor=’#EEEEEE’ are separated by a semicolon which informs the JavaScript interpreter to treat the two as individual statements.

Sponsored Links

Each of these statements carries an instruction for the interpreter. The first one changes the message on the status bar while the second changes the background color. The statements are executed in the order they appear. You might not notice it with this example as the execution very fast.

Change the background color and put a message on the status bar

A similar example is to bring up an alert box and change the background color.

<A HREF="//www.webdevelopersnotes.com" 
onmouseover="window.alert('Go Back To Home Page');
document.bgColor='#EEFFFF'">
Change the background color and bring up an alert box</A>

Change the background color and bring up an alert box

When you pass the mouse cursor over the link above, you’ll notice that the alert box is displayed first, JavaScript execution is stopped. Once the OK button is clicked the next statement is executed that changes the background color.

Meeting another event handler – onmouseout()

To complement onmouseover, JavaScript provides the onmouseout event handler. It captures the event when the mouse pointer is taken off the link object.

<A HREF="http://www.webdevelopersnotes.com/" 
onmouseout="document.bgColor='#FFEEEE'">
Changes the background color when the mouse 
is placed and then taken off the link
</A>

Take your mouse pointer gradually over the link and keep it there… nothing happens; however, the moment you take it off, the background color is changed.

Changes the background color when the mouse is placed and then taken off the link

Using two event handlers for the same object

Here is an irritating psychedelic (?!) effect:

<A HREF="http://www.webdevelopersnotes.com/" 
onmouseover="document.bgColor='#FFFF00'"
onmouseout="document.bgColor='#FFFFEE'">
Move your mouse over me!
</A>

Move your mouse over me!

onmouseover changes the background color to a bright yellow while onmouseout changes it back to the original color.
(Moving the mouse over the link repeatedly will result in a bad headache!)

JavaScript