What are Javascript Events

Events are the techniques used by a user to interact with a webpage, like mouse click, mouse over, key press, keyup, right click etc. Javascript handles both Keyboard based events and mouse based events. Touch based events are also supported in javascript now.

Here is an example of onclick event in javascript using 3 methods.



 <button onclick="alert(this.textContent)">Button </button>
        <!--Obtrusive JavaScript, not recommended-->
 
 <script> 
 document.querySelector("button").onclick=function(){
 alert(this.textContent)
 }  
 </script>  // event handler property, can call single function only
 
 <script>
 document.querySelector("button").addEventListener("click",function(){ alert(this.textContent) })
     
  </script>    // recommended standard way of dealing with Javascript Events
    

This first method works in all browsers, but isn't recommended, as we are writing javascript code in html tag. Second one is neat and clean, but is restricted to single function only.



List of Javascript Events

Here is a list of mouse and keyboard based events.

Event Description Example
onclick script run when mouse left key is clicked.
oncontextmenu script run when mouse right key is clicked.
onmouseover script run when mouse pointer move over an element.
onmouseout script run when mouse pointer move out an element.
onmousmove script run when mouse pointer moves
onmousedown script run when mouse button is pressed
onmouseup script run when mouse button is released.
onsubmit script run when form data is submitted.
onreset script run when reset button is clicked inside form.
onchange script run when elements value or state change.
onselect script run when element is selected.

Select this paragraph

onfocus script run when element is focused
onblur script run when element loose focus.
onkeypress script run when keyboard key is pressed and released .
onkeydown script run when keyboard key is pressed.
onkeyup script run when keyboard key is released . 10 characters left.