EN
JavaScript - onfocus event example
0 points
In this article, we would like to show you onfocus
event example in JavaScript.
Quick solution:
xxxxxxxxxx
1
var myElement = document.querySelector('#my-element');
2
3
myElement.addEventListener('focus', function() {
4
console.log('onfocus event occurred.');
5
});
or:
xxxxxxxxxx
1
<input type="text" onfocus="handleFocus()">
or:
xxxxxxxxxx
1
var myElement = document.querySelector('#my-element');
2
3
myElement.onfocus = function() {
4
console.log('onfocus event occurred.');
5
};
There are three common ways how to use onfocus
event:
- with event listener,
- with element attribute,
- with element property.
In this section, we want to show how to use onfocus
event on input
element via event listener mechanism.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<p>Click on the input field to set focus.</p>
5
<input type="text" id="my-input">
6
<script>
7
var myInput = document.querySelector('#my-input');
8
9
myInput.addEventListener('focus', function() {
10
console.log('onfocus event occurred.');
11
});
12
</script>
13
</body>
14
</html>
In this section, we want to show how to use onfocus
event on input
element via attribute.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<p>Click on the input field to set focus.</p>
5
<input type="text" onfocus="handleFocus()">
6
<script>
7
function handleFocus(){
8
console.log('onfocus event occurred.');
9
}
10
</script>
11
</body>
12
</html>
In this section, we want to show how to use onfocus
event on input
element via property.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<p>Click on the input field to set focus.</p>
5
<input type="text" id="my-input">
6
<script>
7
var myInput = document.querySelector('#my-input');
8
9
myInput.onfocus = function() {
10
console.log('onfocus event occurred.');
11
};
12
</script>
13
</body>
14
</html>