Events in JavaScript

JavaScript Events are the techniques used by a user to interact with webpage, like mouse click, mouse hover, key press, keyup, right click, drag touch etc. Javascript can handle Keyboard based events, mouse based events and Touch Based events. A fully interactive website is not possible without JS Events.

Touch based events and Drag and Drop are also supported in javascript after ES5(2011).

How to add events in JavaScript

There are three ways to add events in javascript.

Event Attribute


<button onclick="alert(this.textContent)">Button</button>
<!--Obtrusive JavaScript, not recommended-->

onclick


<script> 
 document.querySelector("button").onclick=function(){
 alert(this.textContent);
 }  
 </script>  
 <!--add event to element, can assign single function only-->

Event Listener


<script>
 document.querySelector("button").addEventListener("click",function(){ alert(this.textContent) })
     
</script>   
<!--recommended way of dealing with Javascript Events-->
    

This first method is DOM level 0 event and works in all browsers, but isn't recommended, as we are writing javascript code in html. Second is DOM Level 2 events and is neat and clean, but is restricted to single function on same event. We recommended using EventListener in modern web.



List of Javascript Events

Here is a list of mouse, keyboard and touch based events in javascript with example.

← Swipe to view more →


Event Object

Inside every event function or handler, there is a parameter named event or e in short called event object. This event object has properties related to event.

PointerEvent {isTrusted: true, pointerId: 1, width: 1, height: 1, pressure: 0, …}


document.body.addEventListener("click",function(event){
    console.log(event);         // event object
});

document.body.addEventListener("click",event=>{
    console.log(event);         // event object
});

document.body.onclick=function(event){
    console.log(event);         // event object
};

Properties of event object

Here are properties of event object.

Properties of event object
PropertyUse
e.targetrefer to element the event occurred upon
e.keytell which key was pressed
e.whichtell keycode of pressed key
e.preventDefault()prevent default action of element.
e.clientXdistance between click location from body on x-axis
e.clientYdistance between click location from body on y-axis
e.pageXdistance between click location from page left on x-axis
e.pageYdistance between click location from page top on y-axis

onclick

🖱

Javascript click event is a global event for keyboard, mouse and touch interface. This event happen on mouse left click, tap on touch device, and keyboard click on focus (space and enter key only). See example

Using onclick



document.querySelector("button").onclick=function(){
    alert("clicked");
}

Using Event Listener

document.querySelector("button").addEventListener("click",function(){
    alert("clicked");
});

oncontextmenu

🖱

Javascript oncontextmenu is a global event for right click event of mouse or pointing device. This event can happen on pointing devices like mouse only. See example



document.querySelector("button").addEventListener("contextmenu",function(){
    alert("right click");
})

To disable default right click menu, use e.preventDefault(). See example




var btn=document.querySelector("button");

btn.addEventListener('contextmenu',function(e){
    e.preventDefault();
    alert("right click");                    
})

onfocus

🖱

Javascript onfocus is a global event for keyboard, mouse and touch interface. This event happen when user focus on form controls or hyperlink. See example



document.querySelector("input").addEventListener("focus",function(){
    this.value="";
})

onblur

🖱

Javascript onblur is a global event for keyboard, mouse and touch interface. This event happen when user loose focus from focusable element like input. See example




document.querySelector("input").addEventListener("focus",function(){
    this.value="";
});
document.querySelector("input").addEventListener("blur",function(){
    this.value="Name";
});

oninput

🖱

oninput event is global event of input, textarea, and select which invokes when user input data in following controls.




document.querySelector('input[type="range"]').addEventListener("input",function(){
    document.querySelector('span').innerHTML=this.value;
})
        



    document.querySelector("input").addEventListener("input",function(){
        document.querySelector('span').innerHTML=this.value;
    });
            

onchange

🖱

Javascript onchange is a global event for keyboard, mouse and touch interface. This event happen when user change value of select dropdown. See example



document.querySelector("select").addEventListener("change",function(){
    document.querySelector("span").textContent=this.value;
})

onmouseover

🖱

Javascript onmouseover is a global event for mouse. This event happen when user mouse over on an html element. See example

Mouse over in this box

document.querySelector("div.box").addEventListener("mouseover",function(){
  this.innerHTML="Mouse over event done";
  this.style.backgroundColor="#ccc";
})

onmousemove

🖱

Javascript onmousemove is a global event for mouse and touch interface. This event happen when user move mouse over an element. This will happen every time user move his pointer. See example

Mouse over here

document.querySelector("div.box").addEventListener("mousemove",function(e){
   var x=e.clientX;
   var y=e.clientY;
   document.querySelector("span").textContent=`Cursor location is ${x} , ${y}`;
})

onmouseout

🖱

Javascript onmouseout is a global event for mouse and touch interface. This event happen when user remove mouse pointer from an element.. See example

Insert mouse pointer

document.querySelector("div.box").addEventListener("mouseover",function(){
  this.innerHTML="mouse is in now";
});
document.querySelector("div.box").addEventListener("mouseout",function(){
  this.innerHTML="mouse is out now";
});

onmousedown

🖱

Javascript onmousedown is a global event for mouse. This event happen when user starts pressing mouse left click. Event will occur as soon as user initiate pressing mouse left key. See example

click here

document.querySelector("div.box").addEventListener("mousedown",function(){
  this.innerHTML="mouse left key is pressed";
});

onmouseup

🖱

Javascript onmouseup is a global event for mouse. This event happen when user remove mouse left key. It is happening every time user is releasing left key. See example

mouse is out now

document.querySelector("div.box").addEventListener("mouseup",function(){
  this.innerHTML="mouse left key is released";
});

onkeypress


Javascript onkeypress is a global event for keyboard and touch interface. This event happen when user press any keyboard key.

To check keycode, e.which is used where e is parameter in keypress function. To check which key is pressed, String.fromCharCode(e.which) is used. See example


document.querySelector("input").addEventListener("keypress",function(e){
     var x=e.which;    // keycode 
     var y=String.fromCharCode(x);
  this.nextElementSibling.innerHTML=`you pressed ${y} key and keycode is "${x}`;
})

Check Shift key

To check whether Shift key is press with keypress, use e.shiftKey.


document.querySelector("input").addEventListener("keypress",function(e){
     var x=e.which;    // keycode 
     
     if( e.shiftKey){
        document.querySelector("span").textContent="Shift key is pressed";
     }
     else{
        document.querySelector("span").textContent="Shift key was not pressed";
     }
});

Check Alt key

To check alt key , use e.altKey.


Check Ctrl key

To check Ctrl key , use e.ctrlKey.


Check Cmd key in mac

To check Cmd key , use e.metaKey.



onkeydown


Javascript onkeydown is a global event for keyboard and touch interface. This event happen when user start pressing any keyboard key.

Javascript onkeydown event is used in gaming and canvas based applications. See example

Press any key

window.addEventListener("keydown","function(e){
    let x=e.which;
    document.querySelector('span').innerHTML=`keycode is ${x}.`;
})

onkeyup


Javascript onkeyup is a global event for keyboard and touch interface. This event happen when user release any keyboard key.

The onkeyup event is used to calculate no of characters in textbox or textarea. See example




document.querySelector("textarea").addEventListener("keyup","function(){
    let x=this.value.length;
    let y=160-x;
    this.nextElementSibling.innerHTML=`${y} characters left.`;
})

onsubmit

🖱

Javascript onsubmit is a global event for keyboard, mouse and touch interface. This event happen when user submit form data.

The onsubmit event act on click of submit button or enter key press. See example




<form name="contact">
    <input type="text" name="username">
    <button>Submit</button>
</form>

<script>
document.contact.addEventListener("submit",function(e){
    var x=this.username.value;
   console.log(`thanks $x}`);
       
   e.preventDefault();
   // to avoid url redirection after submit
});
<script>

onreset

🖱

Javascript onreset is a global event for keyboard, mouse and touch interface. This event happen when user reset form data using reset button.

If reset button is pressed by mistake, all form data will be erased. To avoid this, use window.confirm() on onreset event . See example




<form name="contact">
    <input type="text" name="username">
    <button type="reset">Reset</button>
    <button>Submit</button>
</form>

<script>
document.contact.addEventListener("reset",function(e){
    var x=window.confirm("would you like to reset?");
    
    if( x==false){e.preventDefault() }          // form reset disabled
    
})
<script>

onselect

🖱

Javascript onselect is a global event for keyboard, mouse and touch interface. This event happen when user select text in textbox or textarea.

The onselect event is used only when selection is done inside input and textarea element.




document.querySelector("input").addEventListener("select","function(){
    this.nextElementSibling.innerHTML="You have selected";
});

oncopy

🖱

Javascript oncopy is a global event for keyboard, mouse and touch interface. This event happen when user copy text from textbox or textarea.

The oncopy event is used only when selected text is copied.




document.querySelector("input").addEventListener("copy",function(){
this.nextElementSibling.innerHTML="text copied";
});

onpaste

🖱

Javascript onpaste is a global event for keyboard, mouse and touch interface. This event happen when user paste text in textbox or textarea.

The onpaste event is used only when selected text is pasted after copying.




document.querySelector("input").addEventListener("paste",function(){
this.nextElementSibling.innerHTML="text pasted";
});

onscroll

🖱

Javascript onscroll is a global event for keyboard, mouse and touch interface. This event happen when user scroll window using mouse, keyboard or touch interface.

The onscroll event is used in many scroll based effects like parallax scrolling, smooth scroll etc.

Scroll window


window.addEventListener("scroll",function(){
    console.log(this.scrollY);  
})

DOMContentLoaded

Javascript DOMContentLoaded is a global event of document object. DOMContentLoaded event happened when all elements in DOM are loaded and parsed including defer scripts.

DOMContentLoaded happens when html tags closing is done as it is the end of webpage. But still images, iframes, ads, async scripts are not finished loading. Once they are finished loading, window.onload events happens.


        console.log("window loading");              // first 
        
    document.addEventListener("DOMContentLoaded",function(){
       console.log("DOM loaded and parsed");               // third
    });
        
        console.log("window still loading");       // second
    

onload

Javascript onload is a global event of window object. This event happen when all requests in a webpage are loaded on DOM.

Onload event is helpful if we want to load DOM content first and then add javascript after DOM Elements are loaded .


    console.log("window loading");              // first 
    
window.addEventListener("load",function(){
   console.log("window loaded");               // third
});
    
    console.log("window still loading");       // second

onreadystatechange

document.onreadystatechange events triggers when the readyState property of document changes. readystatechange event is not cancellable.

readyState

readyState or document.readyState has two values, interactive and complete. interactive means when page is ready for interactions, which happens when all html elements are parsed and complete means when even all media elements are loaded, like image, iframe, video etc.

PropertyMeaningtime (in ms)
loadingdocument is loading0
interactivedocument is loaded and parses, but other resources like images, scripts, css , videos and iframe are still awaited.
completedocument and other resources are loaded.

    document.addEventListener("readystatechange",function(){
        if( this.readyState=="interactive"){
            // same as DOMContentLoaded event
        }
        else if(this.readyState=="complete"){
            // same as load event
        }
    });

Similar Events

  1. readystatechange interactive event is same like document.DOMContentLoaded event
  2. readystatechange complete event is same like window.onload event.