JavaScript — Click Events
Super important article ahead!
In this one, I’m finally going to get around to interacting with the web page! FINALLY. We’re only like… 50 articles in :)
So… here is my new html document.
I have a list of things to do and a button. First I’ll go over how to interact with a button.
When I run this in Live Server the page looks like this:
When I click the button, I want to print something to the console. To do this, you guessed it, we have to use querySelector() to gain access to the button.
Next I have to add an event listener to the button. There is a HUGE list of events you can listen for, but in this situation I want to listen for the “click” event.
The addEventListener method looks for 2 parameters.
- Which event to listen for
- a callback function.
Here I am feeding it the ‘click’ event and the call back function is just an in-line log that says “you clicked the button.”
So now, when I click the button, it prints that message in the console. Easy peezy.
Now I want to knock out this to do list.
When I click the item in the list I want to just put a line through it for now to signify I have completed that task.
Doing this would be easy to do with a forEach loop! SO I’m going to use the querySelectorAll() to get access to all the li tags.
Here I am iterating through each item
in the listItem
. for each one, I’m going to add an event listener that is looking for the click event. For the callback function I want to use a parameter. I’ll just call it e
. I’m using the e.target.style.textDecoration
property and then setting it equal to ‘line-through’.
The end result: