Content Menu

Home-What is JavaScript?

JavaScript tutorials

1. JavaScript Basics

2. JS Simple Coding

3. JS InterActive Content

4. Images and JS

5. JS Functions

6. JavaScript Events

7. JS Conditional

8. JS Loops

9. Other

JavaScript OnMouseover Event

This event handler is used to instruct the browser on What action to take when mouse cursor is moved over an object on the page.

If the concept of events is new to you, it is recommened that you first see lesson on What are Javascript events

Syntax

onmouseover="functionname( )"

The name of function that has to be called when this event occurs.
NOTE: Simple Js code can also be written here instead of calling function, but standard practice with events is to use them with functions.

Example

In this example, we have an image. When mouse is moved over the image, it will be replaced by another image. This has been done using JS Onmouseover event handler.

javascript image

Code Used and Explanation

code used in mouse over event handler

  1. We have an image named 'js_image.jpg' within the body of our page.
  2. We inserted a onmouseover event handler along with its attributes.
  3. We instructed in the attribute that when the onmouseover event activity is detected on this image, the browser should call the function called mouselesson()
  4. We also assigned an ID to the element i.e. the image.

Now the Function explained

  1. We declared a function and named it 'mouselesson'
  2. What that function does is, it locates the element having the ID 'samp'
  3. With the element located, it finds its attribute 'src' and changes its value to 'images/javascript_mouse_over.jpg"

Note-The value of this attribute when the page loaded was 'images/js_image.jpg'. When the function is executed, the value changes and thus a different image appears on the page.

How to change the image back when the mouse leaves it ? For that we will use another event handler called OnMouseOut.

NEXT- JavaScript On Mouse Out Event