To prevent the default action of an event, you call the preventDefault() method of the event object:
event.preventDefault();Code language: CSS (css)The event will continue to propagate as usual unless the event handler explicitly invokes the stopPropagation() method.
Suppose that you have the following checkbox:
<input type="checkbox" name="ckAgree" id="ckAgree"> AgreeCode language: HTML, XML (xml)When you click it, its state will become checked. However, you can use the preventDefault() to not changing its state to be checked:
const ck = document.querySelector('#ckAgree');
ck.addEventListener('click', function (e) {
alert('Sorry! you cannot check this checkbox because of the preventDefault.');
e.preventDefault();
});Code language: JavaScript (javascript)Was this tutorial helpful ?