EN
JavaScript - focus and focusin differences
0 points
In this article, we would like to show you the differences between focus
and focusin
events in JavaScript.
The difference between focus
and focusin
:
focus
- doesn't bubble, can't be delegated,focusin
- bubbles to the parent element, can be delegated.
In this example, we will try to add two event listeners to the my-div
element, but only focusin
will occur when we set focus on the <input>
element inside.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div id="my-div">
5
<p>Click on the input to set focus.</p>
6
<input type="text" />
7
</div>
8
<script>
9
var div = document.getElementById('my-div');
10
11
// this will not work, focus event doesn't bubble
12
div.addEventListener('focus', handleOnfocus, false);
13
14
// this works fine when the input is focused, as the focusin event bubbles
15
div.addEventListener('focusin', handleOnfocusin, false);
16
17
function handleOnfocus() {
18
console.log('onfocus event occurred.');
19
}
20
21
function handleOnfocusin() {
22
console.log('onfocusin event occurred.');
23
}
24
</script>
25
</body>
26
</html>