• Home
  • HTML
    • HTML Introduction
    • HTML Basic
    • HTML Elements
    • HTML Attributes
    • HTML Headings
    • HTML Paragraphs
    • HTML Text Formatting
    • HTML Styles
    • HTML Comments
    • HTML Styles - CSS
    • HTML Links
    • HTML Images
    • HTML Tables
    • HTML Lists
    • HTML Block and Inline Elements
    • HTML class Attribute
    • HTML Forms
    • HTML Media
  • CSS
    • Introduction of CSS
    • CSS Syntax
    • CSS Selectors
    • How To Add CSS
    • CSS Comments
    • CSS Colors
    • CSS Backgrounds
    • CSS Borders
    • CSS Margins
    • CSS Text
    • CSS Lists
    • CSS Tables
    • CSS Box Model
    • CSS Dimension
    • CSS Padding
    • CSS Border
    • CSS Margin
    • CSS Outline
    • CSS Cursors
    • CSS Overflow
    • CSS Units
    • CSS Visual Formatting
    • CSS Display
    • CSS Visibility
    • CSS Position
    • CSS Layers
    • CSS Float
    • CSS Alignment
    • CSS Pseudo-classes
    • CSS Pseudo-elements
    • CSS Media Types
    • CSS Sprites
    • CSS Opacity
    • CSS Attribute Selectors
    • CSS Validation
    • CSS3 Border
    • CSS3 Gradients
    • CSS3 Text Overflow
  • JavaScript
    • JS Introduction
    • JS Getting Started
    • JS Syntax
    • JS Variables
    • JS Generating Output
    • JS Data Types
    • JS Operators
    • JS Events
    • JS Strings
    • JS Numbers
    • JS If Else
    • JS Switch Case
    • JS Arrays
    • JS Sorting Arrays
    • JS Loops
    • JS Functions
    • JS Objects
    • JS DOM Nodes
    • JS DOM Selectors
    • JS DOM Styling
    • JS DOM Get Set Attributes
    • JS DOM Manipulation
    • JS DOM Navigation
    • JS Window
    • JS Screen
    • JS Location
    • JS History
    • JS Navigator
    • JS Dialog Boxes
    • JS Timers
    • JS Date and Time
    • JS Math Operations
    • JS Type Conversions
    • JS Event Listeners
    • JS Event Propagation
    • JS Borrowing Methods
    • JS Hoisting Behavior
    • JS Closures
    • JS Strict Mode
    • JS JSON Parsing
    • JS Error Handling
    • JS Regular Expressions
    • JS Form Validation
    • JS Cookies
    • JS AJAX Requests
    • JS ES6 Features
  • jQuery
    • jQuery Introduction
    • jQuery Syntax
    • jQuery Selectors
    • jQuery Events
    • jQuery Show/Hide
    • jQuery Fade
    • jQuery Slide
    • jQuery Animation
    • jQuery Stop
    • jQuery Chaining
    • jQuery Callback
    • jQuery Get/Set
    • jQuery Insert
    • jQuery Remove
    • jQuery CSS Classes
    • jQuery Style Properties
    • jQuery Dimensions
    • jQuery Traversing
    • jQuery Ancestors
    • jQuery Descendants
    • jQuery Siblings
    • jQuery Filtering
    • jQuery Ajax
    • jQuery Load
    • jQuery Get/Post
    • jQuery No-Conflict
  • PHP
    • PHP Introduction
    • PHP Install
    • PHP Syntax
    • PHP Comments
    • PHP Variables
    • PHP Echo / Print
    • PHP Data Types
    • PHP Strings
    • PHP Constants
    • PHP Operators
    • PHP If...Else...Elseif
    • PHP Switch
    • PHP Loops
    • PHP Functions
    • PHP Arrays
    • PHP Superglobals
    • PHP Date and Time
    • PHP Include
    • PHP File Handling
    • PHP File Upload
    • PHP Cookies
    • PHP Sessions
    • PHP Filters
    • PHP Callback Functions
    • PHP JSON
    • PHP Exceptions
    • PHP What is OOP
    • PHP Classes/Objects
    • PHP Constructor
    • PHP Destructor
    • PHP Access Modifiers
    • PHP Inheritance
    • PHP Abstract Classes
    • PHP Interfaces
    • PHP Traits
    • PHP Static Methods
    • PHP Namespaces
  • SQL
    • Introduction to SQL
    • SQL Create Command
    • SQL ALTER Command
    • SQL Truncate Drop Rename
    • INSERT SQL command
    • UPDATE SQL command
    • DELETE SQL command
    • SQL COMMIT command
    • SQL ROLLBACK command
    • SQL GRANT and REVOKE Command
    • SQL WHERE clause
    • SQL LIKE clause
    • SQL ORDER BY Clause
    • SQL Group By Clause
    • SQL HAVING Clause
    • SQL DISTINCT keyword
    • SQL AND OR operator
    • SQL Constraints
    • SQL Functions
    • SQL JOIN
  • Python
    • Getting started with Python
    • Introduction to IDLE
    • Python 2.x vs. Python 3.x
    • Syntax Rules and First Program
    • Numbers and Math Functions
    • Python Operators
    • Python Variables
    • Python Modules and Functions
    • Python Input and Output
    • Data Types in Python
    • String in Python
    • String Functions in python
    • Lists in Python
    • Utilizing List Elements by Iterating
    • Deleting List Elements & other Functions
    • Dictionaries in Python
    • Functions for Dictionary
    • Tuples in Python
    • Relational and Logical Operators
    • Conditional Statements in Python
    • Looping in Python
    • Define Functions in Python
    • Python-Introduction to OOP
    • Object Oriented Programming in Python
    • Classes in Python
    • The concept of Constructor
    • Destructors - Destroying the Object in Python
    • Inheritance in Python
    • Access Modifers in Python
    • Types of Inheritance
    • Method Overriding in Python
    • Polymorphism
    • static Keyword
    • Operator Overloading Python
    • Introduction to Error Handling
    • Exception Handling: try and except
    • Exeption Handling: finally
    • Exception Handling: raise
    • File Handling
    • Reading and Writing File
    • Introduction to Multithreading
    • Threading Module in Python
    • Thread Object
    • Lock Object
    • RLock Object
    • Event Object
    • Timer Object
    • Condition Object
    • Barrier Object
    • __name__ Variable in Python
    • Iterable and Iterator
    • yield Keyword
    • Python Generators
    • Python Closures
    • Python Decorators
    • @property Decorator in Python
    • Assert Statement
    • Garbage Collection
    • Shallow and Deep Copy
    • Introduction to Logging
    • Configure Log LEVEL, Format etc
    • Python Logging in a file
    • Python Logging Variable Data
    • Python Logging Classes and Functions
    • Python MySQL Introduction
    • Create Database - Python MySQL
    • Create Table - Python MySQL
    • Insert Data in Table
    • Select Data from Table
    • Update data in Table
    • Delete data from Table
    • Drop Table from Database
    • WHERE clause - Python MySQL
    • Order By clause - Python MySQL
    • Limit clause - Python MySQL
    • Table Joins - Python MySQL
  • MongoDB
    • MongoDB Introduction
    • Overview of MongoDB
    • MongoDB vs SQL Databases
    • Advantages of MongoDB
    • When to go for MongoDB
    • Data Modelling in MongoDB
    • Is MongoDB really Schemaless?
    • Installing MongoDB on Windows and Linux
    • Datatypes in MongoDB
    • Create and Drop Database in MongoDB
    • MongoDB: Creating a Collection
    • CRUD Operations in MongoDB
    • Data Relationships in MongoDB
    • Indexing in MongoDB
    • Sorting in MongoDB
    • Aggregation in MongoDB
    • Data Backup and Restoration in MongoDB
    • Sharding in MongoDB
    • Java Integration with MongoDB
  • Elixir
    • Elixir Overview
    • Elixir Environment
    • Elixir Basic Syntax
    • Elixir Data Types
    • Elixir Variables
    • Elixir Operators
    • Elixir Pattern Matching
    • Elixir Decision Making
    • Elixir Strings
    • Elixir Char Lists
    • Elixir Lists and Tuples
    • Elixir Keyword Lists
    • Elixir Maps
    • Elixir Modules
    • Elixir Aliases
    • Elixir Functions
    • Elixir Recursion
    • Elixir Loops
    • Elixir Enumerables
    • Elixir Streams
    • Elixir Structs
    • Elixir Protocols
    • Elixir File I/O
    • Elixir Processes
    • Elixir Sigils
    • Elixir Comprehensions
    • Elixir Typespecs
    • Elixir Behaviours
    • Elixir Errors Handling
    • Elixir Macros
    • Elixir Libraries
  • TypeScript
    • TypeScript Overview
    • Install TypeScript
    • First TypeScript Program
    • Type Annotation
    • TypeScript Variable
    • TypeScript Data Type Number
    • TypeScript Data Type String
    • TypeScript Data Type Boolean
    • TypeScript Arrays
    • TypeScript Tuples
    • TypeScript Enum
    • TypeScript Union
    • TypeScript Any Data Type
    • TypeScript Void Data Type
    • TypeScript Never Data Type
  • Home
  • JS Introduction
  • JS Getting Started
  • JS Syntax
  • JS Variables
  • JS Generating Output
  • JS Data Types
  • JS Operators
  • JS Events
  • JS Strings
  • JS Numbers
  • JS If Else
  • JS Switch Case
  • JS Arrays
  • JS Sorting Arrays
  • JS Loops
  • JS Functions
  • JS Objects
  • JS DOM Nodes
  • JS DOM Selectors
  • JS DOM Styling
  • JS DOM Get Set Attributes
  • JS DOM Manipulation
  • JS DOM Navigation
  • JS Window
  • JS Screen
  • JS Location
  • JS History
  • JS Navigator
  • JS Dialog Boxes
  • JS Timers
  • JS Date and Time
  • JS Math Operations
  • JS Type Conversions
  • JS Event Listeners
  • JS Event Propagation
  • JS Borrowing Methods
  • JS Hoisting Behavior
  • JS Closures
  • JS Strict Mode
  • JS JSON Parsing
  • JS Error Handling
  • JS Regular Expressions
  • JS Form Validation
  • JS Cookies
  • JS AJAX Requests
  • JS ES6 Features
Home >> javascript >> JS Events

JS Events

Welcome to another tutorial. In this tutorial, you will be shown how to handle events in JavaScript.
 

Event Handlers and how to use it

We can describe an event as something that happens when a user interacts with the web page a website. These events may include the user clicking a button or link, entering text into an input box or text area, submitting a form, pressing a key on the keyboard, moving the mouse pointer, and so on. However, modern browsers on their own can trigger events, such as page unload and auto-load.

JavaScript Event Handler or Even Listener can be used to detect and perform a specific task or set of tasks when an event occurs. Event handlers are given names that begin with the word "on", for example, the load event is called 'onload', the click event is called the 'onclick’, and so on.

You can assign an event handler in several ways. One of the ways is to directly add them to the start tag of the HTML element using the special event-handler attributes. Just like the example shown in the paragraph above, to assign a click handler for a button element, you can use the 'on click' attribute, as shown below:

Example :

<button type="button" onclick="alert('Hello World!')">Click</button>

Try With Example

additionally, to separate the JavaScript from HTML, the event handler can be set in an external JavaScript file or within the  ‘<script> and </script> tags,’ like this: ‘</script>’

<button type="button" id="myBtn">Click</button>
<script>
    function sayHello() {
        alert('Hello World!');
    }
    document.getElementById("myBtn").onclick = sayHello;
</script>

Try With Example

Note: recall that HTML attributes are case-insensitive, so ‘onclick’ can be re-written as ‘onClick’,  or ‘OnClick’. However, you should know that HTML value is case-sensitive.

In JavaScript, events can be categorized into four groups and they are keyboard events, document/window events, form events, and mouse events. Though we have other types of events, they will come up in our subsequent lessons in later chapters. Let’s briefly have an overview of some of these groups of events.
 

Keyboard Events

In JavaScript, a keyboard event is initiated when the user presses or releases a key on the keyboard. Let’s take a look at some important keyboard events and their event handler.

 

keydown Event (or ‘onkeydown’)

This type of keyword event occurs when the user presses down a key on the keyboard. The ‘onkeydown’ event handler is used to handle this type of keyboard event. The example here shows the alert message when the keydown event happens.

Example:

<input type="text" onkeydown="alert('You have pressed inside text input!')">
<textarea onkeydown="alert('You have pressed inside textarea!')"></textarea>

Try With Example

 

Keyup Event (‘onkeyup’)

In this case of keyword event, ‘keyup’ event occurs when the user releases a key on the keyboard. This event can be handled with the ‘onkeyup event handler. Below is an example of the alert message you will get when the keyup event occurs.
Example:

<input type="text" onkeyup="alert('You have released key from text input!')">
<textarea onkeyup="alert('You have released key from inside textarea!')"></textarea>

 

Keypress Event (or ‘onkeypress’)

The keypress event occurs when a user presses and releases a key on the keyboard that has a character value unique to it. For example, keys like Ctrl, Esc, Alt, Shift, etc. In essence, these keys mentioned will not generate a keypress event, rather it will generate a ‘keydown’ and a ‘keyup’ event.

The ‘onkeypress’ event handler can be used to handle the keypress. The example here shows the alert message when the keydown event happens.

Example:

<input type="text" onkeypress="alert('You have pressed a key in text input!')">
<textarea onkeypress="alert('You have pressed a key in textarea!')"></textarea> 

 

Form Events

This type of event is experienced when a form control receives or loses focus and also when a user modifies a form control value by doing the following; typing text in a text input, selecting an option in a select box, etc. Below are some important form events and their event handler.


The Focus Event (‘onfocus’)

A focus event happens when the user gives focus to an element on the web page of a website.Hence, the ‘onfocus’ is used to handle the focus event. The example below will show us how ‘onfocus’ works.

Example:

<script>
    function highlightInput(elm){
        elm.style.background = "yellow";
    }    
</script>
<input type="text" onfocus="highlightInput(this)">
<button type="button">Button</button>

Try with example

Note: as we have seen in the example above, keyword inside an event handler refers to the element which has the handler on it 


Blur Event (or ‘onblur’)

In this case, the user takes the focus away from a window or a form element.

The blur event can be handled with the ‘onblur’ event handler. The example here shows the alert message when the text input element loses focus.

Example:

<input type="text" onblur="alert('Text input loses focus!')">
<button type="button">Submit</button>

Try with example

To take the focus away from a form element first click inside of it then press the tab key on the keyboard, give focus on something else, or click outside of it.

 

Change Event (‘onchange’)

This event happens when a user changes the value of a form element. The ‘onchange’ event handler handles the change event. The example here shows the alert message when you change the option in the select box.

Example:

<html>
<head></head>
<body>
           <select onchange="alert('You have select the gender!');">
    		<option>Select</option>
    		<option>Male</option>
    		<option>Female</option>
           </select>
</body>
</html>

Try with example

 

Submit Event (‘onsubmit’)

The submit event occurs on a web page only when the user submits a form on it. You can use the ‘onsubmit’ event handler to handle a submit event. The example here shows the alert message while submitting the form to the server.

Example:

<form action="action.php" method="post" onsubmit="alert('Form data will be submitted to the server!');">
    <label>First Name:</label>
    <input type="text" name="first-name" required>
    <input type="submit" value="Submit">
</form>

 

Mouse Events

A mouse event is an event triggered when the user moves the mouse pointer over an element or clicks some element, etc. The example below will show us how a mouse event works you move a mouse pointer over an element.

 

Click Event (‘onclick’)

This type of event only occurs when a user clicks on an element on a web page. Most times they are links and form elements. The use of ‘onclick’ event handler is used to handle a click event.

The example here shows the alert message when you click on the elements.

<html>
<head></head>
<body>
           <button type="button" onclick="alert('You have clicked a button!');">Click Me</button>
           <a href="#" onclick="alert('You have clicked a link!');">Click Me</a>
</body>
</html>

Try with example

 

Context menu Event (‘oncontextmenu’)

The one important event handler, it occurs when a user clicks the right mouse button on an element to open a context menu. The ‘oncontextmenu’ event handler is used to handle a context menu event.

The example here shows the alert message when you right-click on the elements.

Example:

<html>
<head></head>
<body>
           <button type="button" oncontextmenu="alert('You have right-clicked a button!');">Right Click on Me</button>
<a href="#" oncontextmenu="alert('You have right-clicked a link!');">Right Click on Me</a>
</body>
</html>

Try with example

 

Mouseover Event (onmouseover)

The mouseover event only occurs when a user moves the mouse pointer over an element.

The ‘onmouseover’ event handler is used to handle the mouseover event. The example below shows the alert message if you place a mouse over the elements.

Example:

<html>
<head></head>
<body>
           <button type="button" onmouseover="alert('You have placed mouse pointer over a button!');">Place Mouse Over Me</button>
           <a href="#" onmouseover="alert('You have placed mouse pointer over a link!');">Place Mouse Over Me</a>
</body>
</html>

Try with example

 

Mouseout Event (‘onmouseout’)

The mouseout event occurs if a user while using the mouse moves the mouse pointer outside of an element.

The ‘onmouseout’ event handler is what you can use to handle the mouseout event. The example below shows the alert message if the mouseout event occurs.

Example:

<html>
<head></head>
<body>
           <button type="button" onmouseout="alert('You have moved out of the button!');">Place Mouse Inside Me and Move Out</button>
           <a href="#" onmouseout="alert('You have moved out of the link!');">Place Mouse Inside Me and Move Out</a>
</body>
</html>

Try with example

 

Document/Window Events

Window/document events are triggered when the web page has loaded or the user resizes the browser window. Below are some important form events and their event handler.
 

Load Event (‘onload’)

This web page event occurs when a web page has finished loading in the web browser. The ‘onload’ event handler is used to handle the load event. The example below shows the alert message as soon as the page finishes loading.

Example :

<html>
<head></head>
    <body onload="window.alert('Page is loaded successfully!');">
           <h1>This is a heading</h1>
           <p>This is paragraph of text.</p>
   </body>
</html>

Try with example

 

Unload Event (‘onunload’)

The unload event occurs only when a user leaves the current web page on the website. Therefore, ‘onunload’ event handler is used to handle the unload event. The example below shows the alert message when you try to leave the page.

Example:

<html>
<head></head>
<body onunload="alert('Are you sure you want to leave this page?');">
    <h1>This is a heading</h1>
    <p>This is paragraph of text.</p>
</body>
</html>


Resize Event (‘onresize’)

This event deals with the resizing of a window of a browser. So, it occurs when the user resizes the window of a web browser and also, for minimization and maximization of a window.

The ‘onresize’ event handler is used to handle the resize of an event. The example below shows the alert message when you resize the browser window to a new size.

Example:

<html>
<head></head>
<body>
    <p id="result"></p>
<script>
    function displayWindowSize() {
        var w = window.outerWidth;
        var h = window.outerHeight;
        var txt = "Window size: width=" + w + ", height=" + h;
        document.getElementById("result").innerHTML = txt;
    }
    window.onresize = displayWindowSize;
</script>
</body>
</html>

Try with example

  • Prev
  • Next


-Advertisement-


DeveloperTutorial
[email protected] © 2022-2023 Developers Tutorial All rights reserved.

Follow Us

Facebook Twitter LinkedIn Printerest Reddit

Announcement

Its a big achivement for us, We make a partnership with TutorialWithExample.com for the better content of our users.

Still Need Help ?

Let us now about your issue and a Professional will reach you out.