EN
JavaScript - onblur event example
0
points
In this article, we would like to show you onblur
event example in JavaScript.
Quick solution:
var myElement = document.querySelector('#my-element');
myElement.addEventListener('blur', function() {
console.log('onblur event occurred.');
});
or:
<input type="text" onblur="handleBlur()">
or:
var myElement = document.querySelector('#my-element');
myElement.onblur = function() {
console.log('onblur event occurred.');
};
Practical examples
There are three common ways how to use onblur
event:
- with event listener,
- with element attribute,
- with element property.
In this example, we will execute handleBlur()
when an input field loses focus (onblur
event).
1. Event listener based example
In this section, we want to show how to use onblur
event on input
element via event listener mechanism.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<p>Click on the input field, then click outside it.</p>
<input type="text" id="my-input">
<script>
var myInput = document.querySelector('#my-input');
myInput.addEventListener('blur', function() {
console.log('onblur event occurred.');
});
function handleBlur(){
console.log('onblur event occurred.');
}
</script>
</body>
</html>
2. Attribute based example
In this section, we want to show how to use onblur
event on input
element via attribute.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<p>Click on the input field, then click outside it.</p>
<input type="text" onblur="handleBlur()">
<script>
function handleBlur(){
console.log('onblur event occurred.');
}
</script>
</body>
</html>
3. Property based example
In this section, we want to show how to use onblur
event on input
element via property.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<p>Click on the input field, then click outside it.</p>
<input type="text" id="my-input">
<script>
var myInput = document.querySelector('#my-input');
myInput.onblur = function(){
console.log('onblur event occurred.');
}
</script>
</body>
</html>