Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialYan Kozlovskiy
30,427 PointsWhen should you use event.preventDefault()?
I am not entirely sure when I should use this jQuery method.
3 Answers
Steven Parker
231,269 PointsYou would use this anytime something automatically happens and you want to stop it.
For example: a common use is when you attach a custom button-click handler to a form submit button. If your handler is validating the data and finds it unsuitable, it can use this to prevent the submit from actually happening.
Nicholas Pretorius
18,684 PointsYou can use it when there is a default behaviour for an HTML element. (https://api.jquery.com/event.preventDefault/) For example: when clicking a link, submitting a form, checking a check box etc.
I guess the most common use case would be when you want to bypass an action for some reason.
The DOM Web API has a similar method built in to use directly through JavaScript. https://developer.mozilla.org/en/docs/Web/API/Event/preventDefault
Yan Kozlovskiy
30,427 PointsIs it always for default HTML behavior and nothing else?
Nicholas Pretorius
18,684 PointsGoing by the name of the function and the description of it, I would say yes.
Shafeeq Ahmed
6,058 PointsShafeeq Ahmed
6,058 PointsThere some places the browser has a default actions for some events on some elements. for example if you click on anchor element (link) it will take you to another page. to prevent such default actions you should use this method.