Mouse Event

Course- Javascript >

One of the fundamental purposes of JavaScript is to help make your web pages more interactive for the user. To achieve this, we need to have some mechanisms to detect what the user and the program are doing at any given moment—where the mouse is in the browser window, whether the user has clicked a mouse button or pressed a keyboard key, whether a page has fully loaded in the browser, and so on.

All of these occurrences we refer to as events, and JavaScript has a variety of tools to help us work with them. Let’s take a look at some of the ways we can detect a user’s mouse actions using JavaScript.

JavaScript deals with events by using so-called event handlers. We are going to investigate three of these: onClick, onMouseOver, and onMouseOut.

The onClick Event Handler

The onClick event handler can be applied to nearly all HTML elements visible on a page. One way we can implement it is to add one more attribute to the HTML element:

onclick=" ...some JavaScript code... "
<!DOCTYPE html>
<html>
<head>
<title>onClick Demo</title>
</head>
<body>
<input type="button" onclick="alert('You clicked the button!')"
value="Click Me" />
</body>
</html>                    
                    

The HTML code adds a button to the element of the page, and supplies that button with an onclick attribute. The value given to the onclick attribute is the JavaScript code we want to run when the HTML element (in this case a button) is clicked. When the user clicks on the button, the onclick event is activated (we normally say the event has been “fired”) and the JavaScript statement(s) listed in the value of the attribute are executed.

In this case, there’s just one statement:

alert('You clicked the button!') onclick event

onMouseOver and onMouseOut Event Handlers

When we simply want to detect where the mouse pointer is on the screen with reference to a particular page element, onMouseOver and onMouseOut can help us to do that.

The onMouseOver event is fired when the user’s mouse cursor enters the region of the screen occupied by the element in question. The onMouseOut event, as I’m sure you’ve already guessed, is fired when the cursor leaves that same region.

using onmouseover
<!DOCTYPE html>
<html>
<head>
<title>onMouseOver Demo</title>
</head>
<body>
<img src="image1.png" alt="image 1" onmouseover="alert('You entered
the image!')" />
</body>
</html>                    
                    
onmouseover event

onMouseOver & onMouseOut

<!DOCTYPE html>
<html>
<head>
<title>OnMouseOver Demo</title>
</head>
<body>
<img src="tick.gif" alt="tick" onmouseover="this.src='tick2.gif';"
onmouseout="this.src='tick.gif';" />
</body>
</html>                    
                    
onmouseout event