Kontext
Adding event listeners
Now that you now how to grab specific HTML elements from inside a JS script, you can attach event listeners to them.
Adding event listeners to html elements is like playing the old 'Cluedo' table game. Instead of stating that the murder was done by 'Colonel Mustard, in the Kitchen with the stilleto' you need to answer the same questions but in a different way.
For example we want to hide a paragraph anytime a specific button is clicked.
The previous sentence contains all the information someone is going to need in order to implement this example. The 'Cluedo' questions are still there?
Who triggers the event?
What type of event is that?
What is going to happen anytime this event occurs?
The answer to the first question is 'the button'. You need to grab the specific button that every time is clicked, the paragraph gets vanished. For now let's pretend we have only one button in our HTML page, so we use the querySelector method to grab it and store it in a variable. This happens at line 2.
Then we need to specify the type of the event. In this case is a 'click', this string is passed as a first argument of the addEventListener function that is attached to event target element (in our case the button we grabbed)! This is the answer to the second question.
Regarding the third question, the answer is placed inside the addEventListener function, at the second argument. There we define a function (define, not invoke, the invocation will happen immediately AFTER the event occurs) that will run every time this event is triggered from this element.
In our example above we just console that something was clicked for now.
An event listener can be also removed through the removeEventListener function.
More about event listeners here