Basics of Events in JavaScript

Introduction

 
Events refer to the actions that are detected by a programming language when you perform a specified task.
 
Example:
the onclick event detected by the programming language when you click the mouse button.
 
Events are generally used in combination with the function, implying that when an event occurs, it calls a specified function. An event commonly occurs when a user clicks the mouse button, a web page is loaded, or a form field is changed. Events are handled by a special function, known as an event handler, that handles a specified event when the event is triggered.
 

How to Create an Event handler?

 
JavaScript.jpg
 
In the code above, OnEvent refers to the name of an event followed by an equal sign and the code that executes when the event is triggered.
 
Let's do an exercise.
 

Working with onclick Event

 
The onclick event triggers when you click a control, such as a button control. Let's create a webpage to understand the onclick event:
 
JavaScript1.jpg
 
Here we defined the onclick event that occurs when we click on the "Click Me" button.
 
See the following output
 
JavaScript2.jpg
 
Here this alert box appears because of the onclick event and this event occurs when we click the "Click Me" button.
 
So that is the basic concept of events. There are many events used in JavaScript with HTML. Some of the JavaScript events used in HTML forms are given below:
 
JavaScript3.jpg
 
Some Keyboard Events used in HTML:
  • onkeydown
  • onkeypass
  • onkeyup
Some JavaScript mouse events used in HTML:
  • onclick
  • ondblclick
  • ondrag*
  • ondragend*
  • ondragenter*
  • ondragleave*
  • ondragover*
  • ondragstart*
  • ondrop
  • onmousedown
  • onmousemove
  • onmouseout
  • onmouseover
  • onmouseup
  • onmousewheel*
  • onscroll*
JavaScript4.jpg
 
And so on. There are many other events in JavaScript used in Media elements of HTML and browsers. Try these events yourself. I will explain how these and many other events work in my next article.