EN
JavaScript - onblur event example
0 points
In this article, we would like to show you onblur
event example in JavaScript.
Quick solution:
xxxxxxxxxx
1
var myElement = document.querySelector('#my-element');
2
3
myElement.addEventListener('blur', function() {
4
console.log('onblur event occurred.');
5
});
or:
xxxxxxxxxx
1
<input type="text" onblur="handleBlur()">
or:
xxxxxxxxxx
1
var myElement = document.querySelector('#my-element');
2
3
myElement.onblur = function() {
4
console.log('onblur event occurred.');
5
};
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).
In this section, we want to show how to use onblur
event on input
element via event listener mechanism.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<p>Click on the input field, then click outside it.</p>
5
<input type="text" id="my-input">
6
<script>
7
var myInput = document.querySelector('#my-input');
8
9
myInput.addEventListener('blur', function() {
10
console.log('onblur event occurred.');
11
});
12
13
function handleBlur(){
14
console.log('onblur event occurred.');
15
}
16
</script>
17
</body>
18
</html>
In this section, we want to show how to use onblur
event on input
element via attribute.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<p>Click on the input field, then click outside it.</p>
5
<input type="text" onblur="handleBlur()">
6
<script>
7
function handleBlur(){
8
console.log('onblur event occurred.');
9
}
10
</script>
11
</body>
12
</html>
In this section, we want to show how to use onblur
event on input
element via property.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<p>Click on the input field, then click outside it.</p>
5
<input type="text" id="my-input">
6
<script>
7
var myInput = document.querySelector('#my-input');
8
9
myInput.onblur = function(){
10
console.log('onblur event occurred.');
11
}
12
</script>
13
</body>
14
</html>