Reputation:
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
Reputation: 53245
var element = document.getElementById("ELEMENT_ID");
element.addEventListener("blur", function() { ... your code here ...});
$("#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
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