📜  javascript on focus - Javascript (1)

📅  最后修改于: 2023-12-03 15:31:38.128000             🧑  作者: Mango

JavaScript on focus - Javascript

JavaScript on focus is an event that is triggered when an element gets focus. This event can be used to perform specific actions as soon as a user interacts with an input field or any other form element.

Syntax:
element.onfocus = function() {myFunction()};

Here, element can be any form element, like input, textarea, select, etc., and myFunction() is the function that will be executed when the onfocus event is triggered.

Example:

Let's create an input field and add an onfocus event to it to change the background color of the input field.

<!DOCTYPE html>
<html>
<body>

<input type="text" id="myInput" onfocus="myFunction()">

<script>
function myFunction() {
  document.getElementById("myInput").style.backgroundColor = "yellow";
}
</script>

</body>
</html>

Here, when the user clicks on the input field, the myFunction() function is executed, which changes the background color of the input field to yellow.

Conclusion:

The onfocus event is a powerful tool that can be used to improve the user experience of your web application. By using this event, you can make your forms more interactive and provide instant feedback to your users as soon as they interact with your form elements.