Let's now teach our DOM elements to respond to site user actions. For example, the user clicks somewhere with the mouse, and our code in response will have to process this click and display some information on the screen.
User actions that we can track through JavaScript are called events. Events can be the following: a mouse click on a page element, mouse hover over a page element, or vice versa - the mouse cursor leaves the element, and so on. In addition, there are events that do not depend on user actions, for example, an event when an HTML page is loaded into the browser.
For example, let's make a button, by clicking on which some text will be displayed on the screen as an alert. Let's start with the HTML code for the button:
<input id="button" type="submit">
Now we get a reference to the button into a variable:
let button = document.querySelector('#button');
Now we need to set the reaction of our button
when it is clicked. To do this, JavaScript has
a special method addEventListener
, which
takes the name of the event as the first parameter
(clicking on the button is called 'click'
),
and the second parameter is
a callback function that is executed when
this event occurs.
Let's, for example, by clicking on the button display some text:
button.addEventListener('click', function() {
console.log('!!!');
});
Given 3
buttons:
<input id="button1" type="submit">
<input id="button2" type="submit">
<input id="button3" type="submit">
Make it so that clicking on the first
button displays the number 1
,
clicking on the second button displays
the number 2
, and clicking on
the third button displays the
number 3
.