📜  javascript onblur - Html (1)

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

JavaScript onblur - Html

JavaScript onblur is an event that occurs when an HTML element loses focus. This event is triggered when the user clicks outside of an active HTML element or when the user uses the tab key to move to a different element.

To use the onblur event with JavaScript, you need to specify the function that should be executed when the event is triggered. This function can perform any action that you want, such as updating a variable or hiding a div element.

Syntax

The syntax for using the onblur event with JavaScript is as follows:

element.onblur = function

Here, element is the HTML element that should trigger the event, and function is the JavaScript function that should be executed when the event is triggered.

Example

To illustrate the onblur event in action, consider the following example:

<!DOCTYPE html>
<html>
<body>

<p>Click inside the input field and then click outside of it to trigger the onblur event:</p>

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

<p id="demo"></p>

<script>
function myFunction() {
  var x = document.getElementById("myInput").value;
  document.getElementById("demo").innerHTML = "You entered: " + x;
}
</script>

</body>
</html>

In this example, we have an input element with an onblur attribute that specifies the myFunction() JavaScript function. This function retrieves the value of the input element and displays it in a paragraph element with the id demo.

Conclusion

JavaScript onblur is a useful event for handling user input in web applications. By using the onblur event, you can trigger a JavaScript function when an HTML element loses focus, which can help you validate user input and perform other actions based on user behavior.