25
loading...
This website collects cookies to deliver better user experience
Event.preventDefault()
method is not limited to pure JavaScript language. You can also find it in languages like React and Jquery. But for now, let's stick only with pure JavaScript. Where does we cannot use Event.preventDefault() and some alternatives for it.
Where does the preventDefault() becomes a headache? - passive true/false.
.preventDefault()
:<a>
element with a URL.<form id="form-submission">
element with three types of input elements as its children.
<input type="text" id="input-text">
<input type="checkbox" id="agreement-checkbox">
<input type="submit" id="submit-btn">
<div id="container">
<h1>JS Event - preventDefault()</h1>
<a id="link" href="https://www.google.com">Go to the link</a>
<br><br>
<form id="form-submission">
<label for="input-text">username: </label>
<input type="text" id="input-text" placeholder="Don't type anything here">
<br><br>
<input id="agreement-checkbox" type="checkbox">
<label for="agreement-checkbox">I agree</label>
<br><br>
<input id="submit-btn" type="submit" value="Submit">
<br><br>
</form>
</div>
const container = document.querySelector("#container");
const link = document.querySelector("#link");
const form = document.querySelector('#form-submission');
const input = document.querySelector("#input-text");
const checkbox = document.querySelector("#agreement-checkbox");
const btn = document.querySelector("#submit-btn");
preventDefault()
method.// prevent link
function preventLink(e) {
e.preventDefault();
link.textContent = "Link is prevented";
console.log("Default link behavior is prevented");
}
// prevent submit
function preventSubmit(e) {
if (!checkbox.checked) {
e.preventDefault();
form.innerHTML +=
"Please check the agreement before submitting the form";
console.log("Default submit behavior is prevented");
}
}
.addEventListener()
onclick
within JavaScriptonclick
attribute
to give you some more clarity.// using addEventListener
link.addEventListener("click", preventLink);
btn.addEventListener("click", preventSubmit);
// using onclick within JS
link.onclick = preventLink;
btn.onclick = preventSubmit;
<div id="container">
<h1>JS Event - preventDefault()</h1>
<a id="link" href="https://www.google.com" onclick="preventLink(event)">Go to the link</a>
<br><br>
<form id="form-submission">
<label for="input-text">username: </label>
<input type="text" id="input-text" placeholder="Don't type anything here">
<br><br>
<input id="agreement-checkbox" type="checkbox">
<label for="agreement-checkbox">I agree</label>
<br><br>
<input id="submit-btn" type="submit" value="Submit" onclick="preventSubmit(event)">
<br><br>
</form>
</div>
.preventDefalt()
method in your code and, you may want to make sure whether it works or not at some point. Event.defaultPrevented
comes into the play.function preventSubmit(e) {
if (!checkbox.checked) {
e.preventDefault();
form.innerHTML +=
"Please check the agreement before submitting the form";
console.log("Default submit behavior is prevented");
}
console.log(e.defaultPrevented); // true
}
btn.addEventListener('click', preventSubmit);
.preventDefault()
with the input
event since it is not cancelable. input
event is a read-only property. As an alternative, you can use the readonly
attribute like below.<input type="text" id="input-text" placeholder="Don't type anything here" readonly>
.preventDefault()
to cancel any event, you should find out whether the event is cancelable
or not. If it is not cancelable, you cannot use .preventDefault()
to cancel it.Event.cancelable
property returns true if the event is cancelable otherwise returns false.// check whether an event is cancelable or not
// for input event
input.addEventListener("input", (e) => {
console.log(e.cancelable); // false
});
// for click event
btn.addEventListener('click', (e) => {
if (e.cancelable) {
console.log(e.cancelable); // true
e.preventDefault();
}
});
Event.preventDefault()
method. You cannot stop Event propagation using just only .preventDefault()
. form.addEventListener('click', (e) => {
form.style.borderColor = 'red';
});
function preventSubmit(e) {
if (!checkbox.checked) {
e.preventDefault();
form.innerHTML +=
"Please check the agreement before submitting the form";
console.log("Default submit behavior is prevented");
}
}
btn.addEventListener('click', preventSubmit);
Event.preventDefault()
to the submit button. So it stops submitting the form if the checkbox is unchecked. But, it doesn't stop changing the border-color
of the form
into the red. click
event of the btn
element.preventDefault()
hence, it won't submit the form.form
).click
event there and executes it too.preventDefault()
cannot stop event propagation even it is one of the default behaviors of events..preventDefault()
.preventDefault()
method can do or cannot do. .preventDefault()
?Event.preventDefault()
unless you tend to use the inline onclick
attribute. // prevent link - custom callback
function preventLinkCustom(e, num) {
console.log(num * 2);
e.preventDefault();
link.textContent = "Link is prevented";
console.log("Default link behavior is prevented");
}
// prevent submit - custom callbacks
function preventSubmitCustom(e, num) {
console.log(num * 3);
if (!checkbox.checked) {
e.preventDefault();
form.innerHTML +=
"Please check the agreement before submitting the form";
console.log("Default submit behavior is prevented");
}
}
// using addEventListener()
/* these callbacks are invalid because they will be immediately invoked when the page is loaded. */
link.addEventListener("click", preventLinkCustom(event, 12));
btn.addEventListener("click", preventSubmitCustom(event, 12));
/* output (immediately invoked, got errors, btn isn't executed)
24
Uncaught TypeError: Cannot read property 'preventDefault' of undefined
*/
// using onclick within JS
/* these callbacks are invalid because they will be immediately invoked when the page is loaded. */
link.onclick = preventLinkCustom(event, 12);
btn.onclick = preventSubmitCustom(event, 12);
/* output (immediately invoked, got errors, btn isn't executed)
24
Uncaught TypeError: Cannot read property 'preventDefault' of undefined
*/
inline-onclick
attribute in the HTML and .preventDefault()
in its callback function, we can achieve this requirement like below.// inline onclick
<input id="submit-btn" type="submit" value="Submit" onclick="callback(event, customPara)">
// callback with custom parameters and preventDefault()
function callback(e, customPara) {
// your custom code goes here
e.preventDefault();
}
// prevent link - custom callback
function preventLinkCustom(e, num) {
console.log(num * 2);
e.preventDefault();
link.textContent = "Link is prevented";
console.log("Default link behavior is prevented");
}
// prevent submit - custom callbacks
function preventSubmitCustom(e, num) {
console.log(num * 3);
if (!checkbox.checked) {
e.preventDefault();
container.innerHTML += "Please check the agreement before submitting the form";
console.log("Default submit behavior is prevented");
}
}
<div id="container">
<h1>JS Event - preventDefault()</h1>
<a id="link" href="https://www.google.com" onclick="preventLinkCustom(event, 12)">Go to the link</a>
<br><br>
<form id="form-submission">
<label for="input-text">username: </label>
<input type="text" id="input-text" placeholder="Don't type anything here">
<br><br>
<input id="agreement-checkbox" type="checkbox">
<label for="agreement-checkbox">I agree</label>
<br><br>
<input id="submit-btn" type="submit" value="Submit" onclick="preventSubmitCustom(event, 12)">
<br><br>
</form>
</div>
// inline onclick
<input id="submit-btn" type="submit" value="Submit" onclick="callback(customPara); return false;">
// regular function without Event object as a parameter
function callback(customPara) {
// your custom code goes here
}
// prevent link - custom callbacks
function linkCustom(num) {
console.log(num * 2);
link.textContent = "Link is prevented";
console.log("Default link behavior is prevented");
}
// prevent submit - custom callbacks
function submitCustom(num) {
console.log(num * 3);
if (!checkbox.checked) {
container.innerHTML +=
"Please check the agreement before submitting the form";
console.log("Default submit behavior is prevented");
}
}
<div id="container">
<h1>JS Event - preventDefault()</h1>
<a id="link" href="https://www.google.com" onclick="linkCustom(12); return false;">Go to the link</a>
<br><br>
<form id="form-submission">
<label for="input-text">username: </label>
<input type="text" id="input-text" placeholder="Don't type anything here">
<br><br>
<input id="agreement-checkbox" type="checkbox">
<label for="agreement-checkbox">I agree</label>
<br><br>
<input id="submit-btn" type="submit" value="Submit" onclick="submitCustom(12); return false;">
<br><br>
</form>
</div>
// inline onclick
<input id="submit-btn" type="submit" value="Submit" onclick="return callback(customPara);">
// regular function without Event object as a parameter but with a boolean return value
function callback(customPara) {
// your custom code goes here
return false;
}
// prevent link - custom callbacks
function linkCustom(num) {
console.log(num * 2);
link.textContent = "Link is prevented";
console.log("Default link behavior is prevented");
return false;
}
// prevent submit - custom callbacks
function submitCustom(num) {
console.log(num * 3);
if (!checkbox.checked) {
container.innerHTML +=
"Please check the agreement before submitting the form";
console.log("Default submit behavior is prevented");
return false;
}
return true;
}
<div id="container">
<h1>JS Event - preventDefault()</h1>
<a id="link" href="https://www.google.com" onclick="return linkCustom(12);">Go to the link</a>
<br><br>
<form id="form-submission">
<label for="input-text">username: </label>
<input type="text" id="input-text" placeholder="Don't type anything here">
<br><br>
<input id="agreement-checkbox" type="checkbox">
<label for="agreement-checkbox">I agree</label>
<br><br>
<input id="submit-btn" type="submit" value="Submit" onclick="return submitCustom(12);">
<br><br>
</form>
</div>
/* output
24
"Default link behavior is prevented"
36
"Default submit behavior is prevented"
*/
.preventDefault()
unless we use the inline-onclick to handle the click event. Now let's check whether it can modify the return value that it inherits by default./* no error and no effect by adding return value even using preventDefault() within the callback function */
function preventSubmitCustom(e) {
if (!checkbox.checked) {
e.preventDefault();
container.innerHTML +=
"Please check the agreement before submitting the form";
console.log("Default submit behavior is prevented");
return false;
}
return true;
}
btn.addEventListener('click', preventSubmitCustom);
.preventDefault()
cannot stop that default behavior too.<!-- check the return type using typeof keyword -->
<input id="submit-btn" type="submit" value="Submit" onclick="console.log(typeof preventSubmitCustom(event));">
<!--output: "boolean"-->
Event.addEventListener()
has two optional parameters and one of them is options.addEventListener(type, listener);
addEventListener(type, listener, options);
addEventListener(type, listener, useCapture);
passive: boolean value that, if true, indicates that the function specified by the listener will never call preventDefault(). If a passive listener does call preventDefault(), the user agent will do nothing other than generate a console warning. - MDN
touchstart
event on the mobile. touchstart
event has occurred, Event.preventDefault()
method to execute within the callback function. Event.preventDefault()
within the callback.touchstart
events. Maybe it is smaller than the execution time of a single touchstart
event. It will cause to slow down the web page running..preventDefault()
becomes a headache since the event will slow down the page running, just by only checking for the preventDefault()
method.{passive: true}
option.Event.preventDefault()
method and prevents the page from slowing down.{passive: true}
there. However, it's still good to use while considering all browsers.document.addEventListener('touchstart', (e) => {
console.log('before: ' + e.defaultPrevented); // "before: false"
e.preventDefault();
console.log('after: ' + e.defaultPrevented); // "after: false"
}, { passive: true});
preventDefault()
method, the event should be cancelable - Event.cancelable=true
{passive: true}
as an option within the event listener.Event.defaultPrevented
property to check whether the default behavior of an event is prevented or not.