Others



Events in JavaScript


What is an Event ?

The event is an action, that something happens to HTML elements. For Example When user click on the button, click event triggered. We can execute JavaScript code or function when an event triggered.

In the following example, the click event is triggered by onclick attribute.

<input type='button' onclick="document.write('Button Clicked')" value='Click'>

In the example above, onclick attribute execute the javascript code when button clicks.

We can trigger an event on an element with one of the following methods.

  • Trigger by elements attribute
  • Using DOM object property
  • Using addEventListener() method

Trigger by elements attribute

The following example shows, how to trigger event by an element's attribute.

Example
<input type='button' onclick="func()" value='Click'>
<script>
  function func(){
    document.write("Button Clicked");
  }
</script>
Try it Yourself

DOM object property

We can trigger an event using JavaScript DOM object Properties.

Example
<input type='button' id='btn' value='Click'>
<script>
  document.querySelector("#btn").onclick=function(){
    document.write("Button Clicked");
  }
</script>
Try it Yourself

addEventListener() method

The addEventListener() method is used to bind an event handler to a HTML element.

Syntax
element.addEventListener(event,function);
Example
<input type='button' id='btn' value='Click'>
<script>
  document.querySelector("#btn").addEventListener('click',onclick=function(){
    document.write("Button Clicked");
  });
</script>
Try it Yourself

HTML Events

Event Description
onblur Triggers when an element loses the focus.
onchange Triggers when an element changes.
onclick Triggers when mouse click on the element.
ondblclick Triggers when mouse double click on the element.
onfocus Triggers when an element gets the focus.
onkeydown Triggers when a key is pressed.
onkeypress Triggers when a key is pressed(Indicates which character entered).
onkeyup Triggers when a key is released.
onload Triggers when an object has been loaded.
onmousedown Triggers when a mouse button pressed over the element.
onmouseenter Triggers when a mouse pointer enters the element.
onmouseleave Triggers when a mouse pointer leaves the element.
onmousemove Triggers when a mouse pointer moves over the element.
onmouseout Triggers when a mouse pointer leaves the elements(Triggers on each child element).
onmouseover Triggers when a mouse pointer enters the elements(Triggers on each child element).
onmouseup Triggers when a mouse button released over the element.
onscroll Triggers when an element's scrollbar moves.
onsubmit Triggers when the user submit a form.