user379888
user379888

Reputation:

How to detect if user has left the input field?

Suppose I have an input field,

<input id="city" placeholder="city">

and I want to detect whenever user leaves this field. How can I do so?

Upvotes: 1

Views: 9097

Answers (2)

Tom&#225;š Zato
Tom&#225;š Zato

Reputation: 53245

Normal javascript

var element = document.getElementById("ELEMENT_ID");
element.addEventListener("blur", function() { ... your code here ...});

jQuery

$("#ELEMENT_ID").on("blur",  function() { ... your code here ...});

If, by any chance, you're implementing those self-emptying fields with predefined text, use placeholder attribute. If you're changing style based on focus, use :focus CSS selector. Also, change event is emitted if user leaves the field and changed it's contents.

Upvotes: 8

Fenton
Fenton

Reputation: 251082

When an element loses focus, the onblur event is fired.

var elem = document.getElementById('city');
elem.addEventListener("blur", function( event ) {
    console.log('Elvis has left the city (input)!');
}, true);

https://developer.mozilla.org/en-US/docs/Web/Events/blur

Upvotes: 0

Related Questions