addeventlistener , literally, is to add a listener to the event, why do you do it? Just to make this happen, we can know in time, along with doing something else.
Give a topic: We then give a button on the screen, we hope that when the user moves the mouse, the cursor touches the button, the screen automatically display, "Mouse over!", mouse click, screen then display "Mouse click!", the cursor left, the screen then "mouse left!".
Carefully, this is where event listeners (EventListener) are best to play.
Give the code directly:
<! DOCTYPE html>
<meta charset= "Utf-8" >
<title> Rookie Tutorial (runoob.com) </title>
<body>
<p> The instance uses the AddEventListener () method to add multiple events to the button. </p>
<button id= "Mybtn" > Point me </button>
<p id= "Demo" ></p>
<script>
var x = document.getElementById ("mybtn");
X.addeventlistener ("MouseOver", myFunction);
X.addeventlistener ("click", Mysecondfunction);
X.addeventlistener ("Mouseout", mythirdfunction);
function MyFunction ()
{
document.getElementById ("Demo"). InnerHTML + = "Mouse over!<br>"
}
function Mysecondfunction ()
{
document.getElementById ("Demo"). InnerHTML + = "click!<br>"
}
function Mythirdfunction ()
{
document.getElementById ("Demo"). InnerHTML + = "Mouse away from!<br>"
}
</script>
</body>
Click here to Run!
Analysis:
The basic syntax is:
element. AddEventListener (
Event,
function,
usecapture)
Event: Events, such as the mouseout above, is the mouse out, which needs to be remembered.
function: The trigger functions, which is what we respond to when this event occurs. (The response above is to add a prompt in a P tag.)
Java Script AddEventListener