From the course: JavaScript: Enhancing the DOM

Unlock this course with a free trial

Join today to access over 25,300 courses taught by industry experts.

Working with preventDefault

Working with preventDefault

- [Instructor] Sometimes events have default actions that you might want to prevent. For instance, clicking a link usually takes you to a new page. But what if you want to stop that from happening? You call preventDefault in the event listener. In order to do that, you'll need the event object. preventDefault is a method of the event object that prevents the event's default action, like putting up a stop sign. Here we have a simple page. When I click on the link go to research page, it takes me to example.com, and that is because in here, I'm telling it to do exactly that on line 14. I'm setting the link, but I'm also adding an event listener. I'm doing that in my script.js. As you can see, on line five, I add the event listener to resource link, and I also have the event object available. I can use this to prevent the default event from happening like this. Now, when I click on go to resource page, it's not taking me there. It's actually showing the message because with the…

Contents