JavaScript Events and Eventlistener, Collections and Node lists…30daysofJavascript ==> Day 18
Events and Eventlisteners
Events and event listeners in JavaScript, what are events and event listeners? Are they the same? Well, not quite.
JavaScript events are actions that allow a function to run when they are invoked, for instance, a click can give way to another text or an announcement. Events in JavaScript (from what I have observed, correct me if I am wrong) are usually embedded in an HTML element.
In the snippet above, you would notice the onClick function which sets the button to change the text when it is clicked.
The events in JavaScript are numerous common examples including onClick, onDrag, onLoad and so on. You can check out the reference at this link. JavaScript events are not hard to understand but it is important when you want to use certain invent and for what purpose.
Event listeners on the other hand use the addEventListener() method to listen for an event from the user, it could listen for a key down, mouse over, drag and so on. With the addEventListener() method, new event handlers can be added to an element without it overwriting the past event handlers.
These features are quite easy to understand and one can constantly use the reference in live applications.
DOM Collections and Node Lists
The getElementByTagName() method returns an HTMLCollection object. This object is a node list (collection) of HTML elements. Maybe there is too much technicality here so let's slow down, the HTMLCollection is likened to a bag or box containing a list of a set of selected HTML elements. The elements in this box can be accessed via the length property which starts at an index of 0. We probably think alike if this sounds like an array to you, of course, it does, is there a difference? Yes, arrays are declared differently from node lists, although they can both be accessed with their index, they are two completely different.
Conclusion
This episode shows the use of event listeners, event handlers and node lists.
NB: These topics are very short and that is why I have them combined in one episode.
What is this about?
30daysofjavascript is a series of writing on how I learn to code in JavaScript. These episodes are as simplified as possible and for beginners like me, I hope you find JavaScript less confusing throughout this episode. Thank you as always and see you in the next episode. Check out every episode I have written here.