JavaScript - SPLessons

JavaScript Events

Chapter 20

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

JavaScript Events

JavaScript Events

shape Description

So far, programs consisting of statements that are run and executed when a page is opened, are seen. But, there exist scenarios where the statements will be executed only when there is a response from the users on the forms. For that purpose, JavaScript events are used.

JavaScript Events are actions that happens on the web page. Every website is made responsive through events. JavaScript Events trigger the code to respond to the user’s actions detected by JavaScript. Events are defined in HTML tags. Some examples of events are as follows:

  • Mouse click
  • Web page loading or image loading
  • Selecting an input field in the HTML form
  • Submit an HTML form
  • Keystroke
  • Mouse over hotspot on a web page.

shape Syntax

<HTML_element event_name=”JavaScript code”>

shape More Info

When creating an event, you need to: When the event happens(till then JavaScript code waits), the JavaScript function will be called. For example,

<button onclick=”changeColor()”>Submit</button>
In the above example, onclick event is placed on the button element.

Note:

shape Examples

Onclick Event

This is the most commonly used event in JavaScript. When the user left-clicks on mouse, this event will be generated.

<!Doctype html>
<html>
    <head>
        <meta charset="utf-8"/>
        <title> JavaScript - Events </title> 
        <script type="text/javascript">
         
        </script>
    </head>
   
	<body>
 
		<form>
					<input type="button" value="Click me" onclick="alert('You clicked me');"/>
		</form>
			 
    </body>
     
</html>

Output

onmouseover() event

When the mouse is hovered over HTML element, this event will be generated and works with every HTML element.

onmouseout() event

When the mouse is moved away from specified HTML element, this event will be triggered.

<!DOCTYPE html>
<html>
	<body> 
	 
		<h1 onmouseover="style.color='red'" onmouseout="style.color='black'">Mouse over this text</h1>
	 
	</body>
</html>

Output
The output before placing the mouse on the text is as follows.

Th output after placing the mouse on the text is as follows.

Summary

shape Key Points

  • Any interaction with the webpage content or sending signal to the browser to perform some action is said to be event.
  • onclick, onmouseover() and onmouseover() are some of the JavaScript Events.