How to Create a Blur Event in JavaScript?

Estimated read time 1 min read

To create a “blur” event in JavaScript, you can use the blur event that is native to HTML elements. The blur event occurs when an element loses focus. Here’s an example that logs a message to the console when a text input loses focus:

<input type="text" id="input">

  const input = document.getElementById("input");

  input.addEventListener("blur", function() {
    console.log("Input lost focus.");

In this example, the HTML creates a text input with an id of “input”. The JavaScript uses the document.getElementById method to select the input, and then adds an event listener to the input using the addEventListener method. The addEventListener method takes two arguments: the name of the event to listen for (in this case, “blur”), and a callback function to run when the event occurs. In this example, the callback function simply logs a message to the console.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply