There are a few ways, one way is to add an onclick=”” attribute to the div or button you want to click, another would be setting onclick listeners with javascript. These are both great ways to get your javascript to start interacting with the page.
Onclick and why it’s probably not a good idea
A lot of the times it’s a good idea to keep your logic and your markup separate, in the same way that it’s usually a good idea to keep your styles in a sheet, and not in the markup as style tags, or on your page in a style tag. It’s a common sense, generally accepted, good practice that you’ll hear throughout your career, or at least I’ve always heard that in the places I’ve worked.
Ultimately it’s up to you, but generally speaking it’s nice to go to the javascript file, and get all your javascript, including onclick functions, and go to your markup and find the markup.
Not following that can lead to sticky situations where you don’t know where to look to change the buttons functions, because they’re in two places. Next up the more standard way.
Setting on click listeners, probably a better way
Ah here we go. This is more like it. As you can see in the example above, you set an on click listener by getting a reference to the element in the DOM, the button, or else, whatever you want to click. Oftentimes it’ll be a div if it’s not a button.
The only downside I can see with this, is that sometimes, if you don’t check to see if there’s already a listener on your DOM element, your button or div that you’re targeting, and you’ll end up with two functions triggering. Like so.
When things get more complicated here’s a trick I like to use
Let’s say you need to select something but for some reason you are having trouble attaching event listeners to the objects in the DOM. Perhaps it’s a list of elements generated from an API endpoint. Perhaps it’s something that can be duplicated, or the user has the ability to delete entries, and remake them.
Well never fear, even though I just discribed a situation that make both above methods very difficult to implement, I’ve got your get out of jail free card here.
It’s putting an onclick listener above what you’re targeting, sometimes, on the very <body> itself.
It looks like this.
This is also great, because you can run other logic, check for other things like attributes, see if what’s clicked on is above an element, or an element that’s above it. useful for things like, hey did they click outside of a popup. You can do that with, event.closest(“some_target_id”); That kind of thing.