Preventing Default Behavior

Override default link and form behaviors using event.preventDefault()

Back to Exercises

Prevent Link Navigation

Go to example.com

Prevent Form Submit

Full Code Used in This Demo

HTML

<a id="demoLink" href="https://example.com" target="_blank">Go to example.com</a>
<button id="btnBlock">Block Navigation</button>
<form id="demoForm">
  <input name="email" placeholder="Email">
  <button type="submit">Submit</button>
</form>

CSS

.output { border: 1px solid #c7d2fe; border-radius: 8px; padding: 10px; }

JavaScript

let block = false;
const link = document.getElementById('demoLink');
link.addEventListener('click', (e) => { if (block) e.preventDefault(); });