Event/preventDefault interface ¶
Description ¶
The Event interface’s preventDefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be .
The event continues to propagate as usual, unless one of its event listeners calls stopPropagation() or stopImmediatePropagation(), either of which terminates propagation at once.
As noted below, calling preventDefault() for a non-cancelable event, such as one dispatched via EventTarget.dispatchEvent(), without specifying cancelable: true has no effect.
Examples ¶
Blocking default click handling ¶
Toggling a checkbox is the default action of clicking on a checkbox.
This example demonstrates how to prevent that from happening:
JavaScript ¶
1 document.querySelector("#id-checkbox").addEventListener("click", function(event) {
2 document.getElementById("output-box").innerHTML += "Sorry! <code>preventDefault()</code> won't let you check this!<br>";
3 event.preventDefault();
4 }, false);
Blocking carriage return + [‘a’..’z’] ¶
1 /**
2 * disable_carriage_return()
3 * On inactive le traitement du retour chariot ainsi que la saisie des lettres
4 * de a à z.
5 * Voir https://developer.mozilla.org/en-US/docs/Web/API/Element/keydown_event
6 *
7 */
8 function disable_carriage_return() {
9 console.log(`disable_carriage_return()`);
10 const CHAR_CARRIAGE_RETURN_13 = 13;
11 const CHAR_a_65 = 65;
12 const CHAR_z_90 = 90;
13 {% for tuple_indice, v in dict_fiches_temps.items %}
14 document.getElementById('id_fiches_temps_{{ v }}-temps_impute').addEventListener("keydown", event => {
15 console.log(`${event.code}=>${event.keyCode}`);
16 if (event.keyCode === CHAR_CARRIAGE_RETURN_13) {
17 // saisie du retour chariot bloquée
18 event.preventDefault();
19 } else if ((event.keyCode < CHAR_a_65) || (event.keyCode > CHAR_z_90)) {
20 // saisie des lettres de a à z bloquée
21 event.preventDefault();
22 }
23 });
24 {% endfor %}
25 };