jQuery blur() method attaches an event handler function to html elements. This event handler function executes when a form field loses focus. This method works just opposite to the focus() method. The difference between focus() and blur() method is that the focus event is triggered when a form field gets focus while blur event is triggered when a form field loses focus.
jQuery blur() method Syntax
$("input").blur(function(){ //code to execute when a form field loses focus. });
Here blur() method attaches the event handler function where we write our custom code to the input html elements. This custom code inside event handler function executes when the form field loses focus.
jQuery blur() Example
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <script> $(document).ready(function(){ $("input").blur(function(){ $(this).css("background-color", "#eee"); }); }); </script> </head> <body> <h2>jQuery blur event example on Beginnersbook.com</h2> Your Name: <input type="text" name="name"><br> Your Age: <input type="text" name="age"> </body> </html>
Output:
Before the form field loses focus:
This screenshot is taken when the page is loaded in browser and no activity is performed on the page.
After the form field loses focus:
This screenshot is taken after the first form field loses focus. We first clicked inside the first input box and then clicked outside to lose the focus, as you can see the background colour of the form field gets changed to #eee because the field lost the focus.
This logic of changing the background colour is written inside the event handler function which is associated to the input html elements using blur() method.
Leave a Reply