I am using the event listener structure like below to do some stuff when the input box loses focus.
But it won't work. What event should I listen to, to get the moment the input box loses the cursor inside it (i.e. user clicks outside of it)?
document.getElementById('div inside which input is located')
.addEventListener( 'blur', function(e){
if(event.target.className=='editInput'){
doStuff(event.target);
}
} , false );
The onfocusout event occurs when an element is about to lose focus. Tip: The onfocusout event is similar to the onblur event. The main difference is that the onblur event does not bubble. Therefore, if you want to find out whether an element or its child loses focus, you should use the onfocusout event.
To detect if the element has the focus in JavaScript, you can use the read-only property activeElement of the document object. const elem = document. activeElement; The activeElement returns the currently focused element in the document.
The onblur event occurs when an object loses focus.
To set focus to an HTML form element, the focus() method of JavaScript can be used. To do so, call this method on an object of the element that is to be focused, as shown in the example. Example 1: The focus() method is set to the input tag when user clicks on Focus button.
The correct event is onBlur. Look at this code:
<!DOCTYPE html>
<html>
<head>
<title>element</title>
<script type="text/javascript">
function message() {
var text = document.getElementById("test").value;
alert(text);
}
</script>
</head>
<body>
<input type="text" name="test" id="test">
<script type="text/javascript">
document.getElementById("test").onblur=message;
</script>
</body>
</html>
It works and prints the content of the input when it loses focus. Maybe your error is that you attached the event to the div and not to the input?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With