diff --git a/files/en-us/learn_web_development/core/scripting/loops/index.md b/files/en-us/learn_web_development/core/scripting/loops/index.md index de9d292dd8972bf..9ad888edc334ab5 100644 --- a/files/en-us/learn_web_development/core/scripting/loops/index.md +++ b/files/en-us/learn_web_development/core/scripting/loops/index.md @@ -73,10 +73,8 @@ const btn = document.querySelector("button"); const canvas = document.querySelector("canvas"); const ctx = canvas.getContext("2d"); -document.addEventListener("DOMContentLoaded", () => { - canvas.width = document.documentElement.clientWidth; - canvas.height = document.documentElement.clientHeight; -}); +canvas.width = document.documentElement.clientWidth; +canvas.height = document.documentElement.clientHeight; function random(number) { return Math.floor(Math.random() * number); diff --git a/files/en-us/learn_web_development/extensions/forms/form_validation/index.md b/files/en-us/learn_web_development/extensions/forms/form_validation/index.md index 0c6ee09f4f6d1a8..86d46e1c9afb561 100644 --- a/files/en-us/learn_web_development/extensions/forms/form_validation/index.md +++ b/files/en-us/learn_web_development/extensions/forms/form_validation/index.md @@ -800,8 +800,8 @@ const setEmailClass = (isValid) => { }; // Update error message and visibility -const updateError = (isValidInput) => { - if (isValidInput) { +const updateError = (isValid) => { + if (isValid) { error.textContent = ""; error.removeAttribute("class"); } else { @@ -810,32 +810,27 @@ const updateError = (isValidInput) => { } }; -// Initialize email validity on page load -const initializeValidation = () => { - const emailInput = isValidEmail(); - setEmailClass(emailInput); -}; - // Handle input event to update email validity const handleInput = () => { - const emailInput = isValidEmail(); - setEmailClass(emailInput); - updateError(emailInput); + const validity = isValidEmail(); + setEmailClass(validity); + updateError(validity); }; // Handle form submission to show error if email is invalid const handleSubmit = (event) => { event.preventDefault(); - const emailInput = isValidEmail(); - setEmailClass(emailInput); - updateError(emailInput); + const validity = isValidEmail(); + setEmailClass(validity); + updateError(validity); }; // Now we can rebuild our validation constraint // Because we do not rely on CSS pseudo-class, we have to // explicitly set the valid/invalid class on our email field -window.addEventListener("load", initializeValidation); +const validity = isValidEmail(); +setEmailClass(validity); // This defines what happens when the user types in the field email.addEventListener("input", handleInput); // This defines what happens when the user tries to submit the data diff --git a/files/en-us/learn_web_development/extensions/forms/how_to_build_custom_form_controls/example_2/index.md b/files/en-us/learn_web_development/extensions/forms/how_to_build_custom_form_controls/example_2/index.md index c5ccff8c89dc598..42d95f81cd4d2ca 100644 --- a/files/en-us/learn_web_development/extensions/forms/how_to_build_custom_form_controls/example_2/index.md +++ b/files/en-us/learn_web_development/extensions/forms/how_to_build_custom_form_controls/example_2/index.md @@ -159,12 +159,10 @@ This is the second example that explain [how to build custom form widgets](/en-U ### JavaScript ```js -window.addEventListener("load", () => { - const form = document.querySelector("form"); +const form = document.querySelector("form"); - form.classList.remove("no-widget"); - form.classList.add("widget"); -}); +form.classList.remove("no-widget"); +form.classList.add("widget"); ``` ### Result diff --git a/files/en-us/learn_web_development/extensions/forms/how_to_build_custom_form_controls/example_3/index.md b/files/en-us/learn_web_development/extensions/forms/how_to_build_custom_form_controls/example_3/index.md index 28598fb3b7545d2..254cffb8496295c 100644 --- a/files/en-us/learn_web_development/extensions/forms/how_to_build_custom_form_controls/example_3/index.md +++ b/files/en-us/learn_web_development/extensions/forms/how_to_build_custom_form_controls/example_3/index.md @@ -199,42 +199,38 @@ function highlightOption(select, option) { // Event binding // // ------------- // -window.addEventListener("load", () => { - const form = document.querySelector("form"); +const form = document.querySelector("form"); - form.classList.remove("no-widget"); - form.classList.add("widget"); -}); +form.classList.remove("no-widget"); +form.classList.add("widget"); -window.addEventListener("load", () => { - const selectList = document.querySelectorAll(".select"); +const selectList = document.querySelectorAll(".select"); - selectList.forEach((select) => { - const optionList = select.querySelectorAll(".option"); +selectList.forEach((select) => { + const optionList = select.querySelectorAll(".option"); - optionList.forEach((option) => { - option.addEventListener("mouseover", () => { - highlightOption(select, option); - }); + optionList.forEach((option) => { + option.addEventListener("mouseover", () => { + highlightOption(select, option); }); + }); - select.addEventListener("click", (event) => { - toggleOptList(select); - }); + select.addEventListener("click", (event) => { + toggleOptList(select); + }); - select.addEventListener("focus", (event) => { - activeSelect(select, selectList); - }); + select.addEventListener("focus", (event) => { + activeSelect(select, selectList); + }); - select.addEventListener("blur", (event) => { - deactivateSelect(select); - }); + select.addEventListener("blur", (event) => { + deactivateSelect(select); + }); - select.addEventListener("keyup", (event) => { - if (event.key === "Escape") { - deactivateSelect(select); - } - }); + select.addEventListener("keyup", (event) => { + if (event.key === "Escape") { + deactivateSelect(select); + } }); }); ``` diff --git a/files/en-us/learn_web_development/extensions/forms/how_to_build_custom_form_controls/example_4/index.md b/files/en-us/learn_web_development/extensions/forms/how_to_build_custom_form_controls/example_4/index.md index 2464c664206c7b3..064ec7a69922690 100644 --- a/files/en-us/learn_web_development/extensions/forms/how_to_build_custom_form_controls/example_4/index.md +++ b/files/en-us/learn_web_development/extensions/forms/how_to_build_custom_form_controls/example_4/index.md @@ -215,78 +215,72 @@ function getIndex(select) { // Event binding // // ------------- // -window.addEventListener("load", () => { - const form = document.querySelector("form"); +const form = document.querySelector("form"); - form.classList.remove("no-widget"); - form.classList.add("widget"); -}); +form.classList.remove("no-widget"); +form.classList.add("widget"); -window.addEventListener("load", () => { - const selectList = document.querySelectorAll(".select"); +const selectList = document.querySelectorAll(".select"); - selectList.forEach((select) => { - const optionList = select.querySelectorAll(".option"); +selectList.forEach((select) => { + const optionList = select.querySelectorAll(".option"); - optionList.forEach((option) => { - option.addEventListener("mouseover", () => { - highlightOption(select, option); - }); + optionList.forEach((option) => { + option.addEventListener("mouseover", () => { + highlightOption(select, option); }); + }); - select.addEventListener("click", (event) => { - toggleOptList(select); - }); + select.addEventListener("click", (event) => { + toggleOptList(select); + }); - select.addEventListener("focus", (event) => { - activeSelect(select, selectList); - }); + select.addEventListener("focus", (event) => { + activeSelect(select, selectList); + }); - select.addEventListener("blur", (event) => { - deactivateSelect(select); - }); + select.addEventListener("blur", (event) => { + deactivateSelect(select); }); }); -window.addEventListener("load", () => { - const selectList = document.querySelectorAll(".select"); +const selectList = document.querySelectorAll(".select"); - selectList.forEach((select) => { - const optionList = select.querySelectorAll(".option"); - const selectedIndex = getIndex(select); +selectList.forEach((select) => { + const optionList = select.querySelectorAll(".option"); + const selectedIndex = getIndex(select); - select.tabIndex = 0; - select.previousElementSibling.tabIndex = -1; + select.tabIndex = 0; + select.previousElementSibling.tabIndex = -1; - updateValue(select, selectedIndex); + updateValue(select, selectedIndex); - optionList.forEach((option, index) => { - option.addEventListener("click", (event) => { - updateValue(select, index); - }); + optionList.forEach((option, index) => { + option.addEventListener("click", (event) => { + updateValue(select, index); }); + }); - select.addEventListener("keyup", (event) => { - let index = getIndex(select); - - if (event.key === "Escape") { - deactivateSelect(select); - } - if (event.key === "ArrowDown" && index < optionList.length - 1) { - index++; - event.preventDefault(); - } - if (event.key === "ArrowUp" && index > 0) { - index--; - event.preventDefault(); - } - - if (event.key === "Enter" || event.key === " ") { - toggleOptList(select); - } + select.addEventListener("keyup", (event) => { + let index = getIndex(select); - updateValue(select, index); - }); + if (event.key === "Escape") { + deactivateSelect(select); + } + if (event.key === "ArrowDown" && index < optionList.length - 1) { + index++; + event.preventDefault(); + } + if (event.key === "ArrowUp" && index > 0) { + index--; + event.preventDefault(); + } + + if (event.key === "Enter" || event.key === " ") { + toggleOptList(select); + } + + updateValue(select, index); }); }); ``` diff --git a/files/en-us/learn_web_development/extensions/forms/how_to_build_custom_form_controls/example_5/index.md b/files/en-us/learn_web_development/extensions/forms/how_to_build_custom_form_controls/example_5/index.md index 4c2a2ee19c84e49..22f3ae38bedea04 100644 --- a/files/en-us/learn_web_development/extensions/forms/how_to_build_custom_form_controls/example_5/index.md +++ b/files/en-us/learn_web_development/extensions/forms/how_to_build_custom_form_controls/example_5/index.md @@ -221,68 +221,64 @@ function getIndex(select) { // Event binding // // ------------- // -window.addEventListener("load", () => { - const form = document.querySelector("form"); +const form = document.querySelector("form"); - form.classList.remove("no-widget"); - form.classList.add("widget"); -}); - -window.addEventListener("load", () => { - const selectList = document.querySelectorAll(".select"); +form.classList.remove("no-widget"); +form.classList.add("widget"); - selectList.forEach((select) => { - const optionList = select.querySelectorAll(".option"); - const selectedIndex = getIndex(select); +const selectList = document.querySelectorAll(".select"); - select.tabIndex = 0; - select.previousElementSibling.tabIndex = -1; +selectList.forEach((select) => { + const optionList = select.querySelectorAll(".option"); + const selectedIndex = getIndex(select); - updateValue(select, selectedIndex); + select.tabIndex = 0; + select.previousElementSibling.tabIndex = -1; - optionList.forEach((option, index) => { - option.addEventListener("mouseover", () => { - highlightOption(select, option); - }); + updateValue(select, selectedIndex); - option.addEventListener("click", (event) => { - updateValue(select, index); - }); + optionList.forEach((option, index) => { + option.addEventListener("mouseover", () => { + highlightOption(select, option); }); - select.addEventListener("click", (event) => { - toggleOptList(select); + option.addEventListener("click", (event) => { + updateValue(select, index); }); + }); - select.addEventListener("focus", (event) => { - activeSelect(select, selectList); - }); + select.addEventListener("click", (event) => { + toggleOptList(select); + }); - select.addEventListener("blur", (event) => { - deactivateSelect(select); - }); + select.addEventListener("focus", (event) => { + activeSelect(select, selectList); + }); - select.addEventListener("keyup", (event) => { - let index = getIndex(select); - - if (event.key === "Escape") { - deactivateSelect(select); - } - if (event.key === "ArrowDown" && index < optionList.length - 1) { - index++; - event.preventDefault(); - } - if (event.key === "ArrowUp" && index > 0) { - index--; - event.preventDefault(); - } - - if (event.key === "Enter" || event.key === " ") { - toggleOptList(select); - } + select.addEventListener("blur", (event) => { + deactivateSelect(select); + }); - updateValue(select, index); - }); + select.addEventListener("keyup", (event) => { + let index = getIndex(select); + + if (event.key === "Escape") { + deactivateSelect(select); + } + if (event.key === "ArrowDown" && index < optionList.length - 1) { + index++; + event.preventDefault(); + } + if (event.key === "ArrowUp" && index > 0) { + index--; + event.preventDefault(); + } + + if (event.key === "Enter" || event.key === " ") { + toggleOptList(select); + } + + updateValue(select, index); }); }); ``` diff --git a/files/en-us/learn_web_development/extensions/forms/how_to_build_custom_form_controls/index.md b/files/en-us/learn_web_development/extensions/forms/how_to_build_custom_form_controls/index.md index cdc4d79bb2b5fad..088a4c7873c482a 100644 --- a/files/en-us/learn_web_development/extensions/forms/how_to_build_custom_form_controls/index.md +++ b/files/en-us/learn_web_development/extensions/forms/how_to_build_custom_form_controls/index.md @@ -713,10 +713,8 @@ This CSS visually hides one of the elements, but it is still available to screen Now we need a JavaScript switch to determine if the script is running or not. This switch is a couple of lines: if at page load time our script is running, it will remove the `no-widget` class and add the `widget` class, thereby swapping the visibility of the {{HTMLElement("select")}} element and the custom control. ```js -window.addEventListener("load", () => { - document.body.classList.remove("no-widget"); - document.body.classList.add("widget"); -}); +document.body.classList.remove("no-widget"); +document.body.classList.add("widget"); ``` #### Without JS @@ -898,12 +896,10 @@ Check out the [full source code](/en-US/docs/Learn_web_development/Extensions/Fo ``` ```js hidden -window.addEventListener("load", () => { - const form = document.querySelector("form"); +const form = document.querySelector("form"); - form.classList.remove("no-widget"); - form.classList.add("widget"); -}); +form.classList.remove("no-widget"); +form.classList.add("widget"); ``` {{EmbedLiveSample("With_JS",120,130)}} @@ -995,60 +991,57 @@ You need these to handle the various states of custom control. Next, we bind these functions to the appropriate events: ```js -// We handle the event binding when the document is loaded. -window.addEventListener("load", () => { - const selectList = document.querySelectorAll(".select"); - - // Each custom control needs to be initialized - selectList.forEach((select) => { - // as well as all its `option` elements - const optionList = select.querySelectorAll(".option"); - - // Each time a user hovers their mouse over an option, we highlight the given option - optionList.forEach((option) => { - option.addEventListener("mouseover", () => { - // Note: the `select` and `option` variable are closures - // available in the scope of our function call. - highlightOption(select, option); - }); - }); +const selectList = document.querySelectorAll(".select"); - // Each times the user clicks on or taps a custom select element - select.addEventListener("click", (event) => { - // Note: the `select` variable is a closure - // available in the scope of our function call. +// Each custom control needs to be initialized +selectList.forEach((select) => { + // as well as all its `option` elements + const optionList = select.querySelectorAll(".option"); - // We toggle the visibility of the list of options - toggleOptList(select); + // Each time a user hovers their mouse over an option, we highlight the given option + optionList.forEach((option) => { + option.addEventListener("mouseover", () => { + // Note: the `select` and `option` variable are closures + // available in the scope of our function call. + highlightOption(select, option); }); + }); - // In case the control gains focus - // The control gains the focus each time the user clicks on it or each time - // they use the tabulation key to access the control - select.addEventListener("focus", (event) => { - // Note: the `select` and `selectList` variable are closures - // available in the scope of our function call. + // Each times the user clicks on or taps a custom select element + select.addEventListener("click", (event) => { + // Note: the `select` variable is a closure + // available in the scope of our function call. - // We activate the control - activeSelect(select, selectList); - }); + // We toggle the visibility of the list of options + toggleOptList(select); + }); - // In case the control loses focus - select.addEventListener("blur", (event) => { - // Note: the `select` variable is a closure - // available in the scope of our function call. + // In case the control gains focus + // The control gains the focus each time the user clicks on it or each time + // they use the tabulation key to access the control + select.addEventListener("focus", (event) => { + // Note: the `select` and `selectList` variable are closures + // available in the scope of our function call. - // We deactivate the control - deactivateSelect(select); - }); + // We activate the control + activeSelect(select, selectList); + }); - // Loose focus if the user hits `esc` - select.addEventListener("keyup", (event) => { - // deactivate on keyup of `esc` - if (event.key === "Escape") { - deactivateSelect(select); - } - }); + // In case the control loses focus + select.addEventListener("blur", (event) => { + // Note: the `select` variable is a closure + // available in the scope of our function call. + + // We deactivate the control + deactivateSelect(select); + }); + + // Loose focus if the user hits `esc` + select.addEventListener("keyup", (event) => { + // deactivate on keyup of `esc` + if (event.key === "Escape") { + deactivateSelect(select); + } }); }); ``` @@ -1227,46 +1220,42 @@ function highlightOption(select, option) { option.classList.add("highlight"); } -window.addEventListener("load", () => { - const form = document.querySelector("form"); +const form = document.querySelector("form"); - form.classList.remove("no-widget"); - form.classList.add("widget"); -}); +form.classList.remove("no-widget"); +form.classList.add("widget"); -window.addEventListener("load", () => { - const selectList = document.querySelectorAll(".select"); +const selectList = document.querySelectorAll(".select"); - selectList.forEach((select) => { - const optionList = select.querySelectorAll(".option"); +selectList.forEach((select) => { + const optionList = select.querySelectorAll(".option"); - optionList.forEach((option) => { - option.addEventListener("mouseover", () => { - highlightOption(select, option); - }); + optionList.forEach((option) => { + option.addEventListener("mouseover", () => { + highlightOption(select, option); }); + }); - select.addEventListener( - "click", - (event) => { - toggleOptList(select); - }, - false, - ); + select.addEventListener( + "click", + (event) => { + toggleOptList(select); + }, + false, + ); - select.addEventListener("focus", (event) => { - activeSelect(select, selectList); - }); + select.addEventListener("focus", (event) => { + activeSelect(select, selectList); + }); - select.addEventListener("blur", (event) => { - deactivateSelect(select); - }); + select.addEventListener("blur", (event) => { + deactivateSelect(select); + }); - select.addEventListener("keyup", (event) => { - if (event.key === "Escape") { - deactivateSelect(select); - } - }); + select.addEventListener("keyup", (event) => { + if (event.key === "Escape") { + deactivateSelect(select); + } }); }); ``` @@ -1322,60 +1311,57 @@ function getIndex(select) { With these two functions, we can bind the native controls to the custom ones: ```js -// We handle event binding when the document is loaded. -window.addEventListener("load", () => { - const selectList = document.querySelectorAll(".select"); +const selectList = document.querySelectorAll(".select"); - // Each custom control needs to be initialized - selectList.forEach((select) => { - const optionList = select.querySelectorAll(".option"); - const selectedIndex = getIndex(select); +// Each custom control needs to be initialized +selectList.forEach((select) => { + const optionList = select.querySelectorAll(".option"); + const selectedIndex = getIndex(select); - // We make our custom control focusable - select.tabIndex = 0; + // We make our custom control focusable + select.tabIndex = 0; - // We make the native control no longer focusable - select.previousElementSibling.tabIndex = -1; + // We make the native control no longer focusable + select.previousElementSibling.tabIndex = -1; - // We make sure that the default selected value is correctly displayed - updateValue(select, selectedIndex); + // We make sure that the default selected value is correctly displayed + updateValue(select, selectedIndex); - // Each time a user clicks on an option, we update the value accordingly - optionList.forEach((option, index) => { - option.addEventListener("click", (event) => { - updateValue(select, index); - }); + // Each time a user clicks on an option, we update the value accordingly + optionList.forEach((option, index) => { + option.addEventListener("click", (event) => { + updateValue(select, index); }); + }); - // Each time a user uses their keyboard on a focused control, we update the value accordingly - select.addEventListener("keyup", (event) => { - let index = getIndex(select); - // When the user hits the Escape key, deactivate the custom control - if (event.key === "Escape") { - deactivateSelect(select); - } - - // When the user hits the down arrow, we jump to the next option - if (event.key === "ArrowDown" && index < optionList.length - 1) { - index++; - // Prevent the default action of the ArrowDown key press. - // Without this, the page would scroll down when the ArrowDown key is pressed. - event.preventDefault(); - } - - // When the user hits the up arrow, we jump to the previous option - if (event.key === "ArrowUp" && index > 0) { - index--; - // Prevent the default action of the ArrowUp key press. - event.preventDefault(); - } - if (event.key === "Enter" || event.key === " ") { - // If Enter or Space is pressed, toggle the option list - toggleOptList(select); - } + // Each time a user uses their keyboard on a focused control, we update the value accordingly + select.addEventListener("keyup", (event) => { + let index = getIndex(select); + // When the user hits the Escape key, deactivate the custom control + if (event.key === "Escape") { + deactivateSelect(select); + } + + // When the user hits the down arrow, we jump to the next option + if (event.key === "ArrowDown" && index < optionList.length - 1) { + index++; + // Prevent the default action of the ArrowDown key press. + // Without this, the page would scroll down when the ArrowDown key is pressed. + event.preventDefault(); + } + + // When the user hits the up arrow, we jump to the previous option + if (event.key === "ArrowUp" && index > 0) { + index--; + // Prevent the default action of the ArrowUp key press. + event.preventDefault(); + } + if (event.key === "Enter" || event.key === " ") { + // If Enter or Space is pressed, toggle the option list + toggleOptList(select); + } - updateValue(select, index); - }); + updateValue(select, index); }); }); ``` @@ -1572,72 +1558,66 @@ function getIndex(select) { return nativeWidget.selectedIndex; } -window.addEventListener("load", () => { - const form = document.querySelector("form"); +const form = document.querySelector("form"); - form.classList.remove("no-widget"); - form.classList.add("widget"); -}); +form.classList.remove("no-widget"); +form.classList.add("widget"); -window.addEventListener("load", () => { - const selectList = document.querySelectorAll(".select"); +const selectList = document.querySelectorAll(".select"); - selectList.forEach((select) => { - const optionList = select.querySelectorAll(".option"); +selectList.forEach((select) => { + const optionList = select.querySelectorAll(".option"); - optionList.forEach((option) => { - option.addEventListener("mouseover", () => { - highlightOption(select, option); - }); + optionList.forEach((option) => { + option.addEventListener("mouseover", () => { + highlightOption(select, option); }); + }); - select.addEventListener("click", (event) => { - toggleOptList(select); - }); + select.addEventListener("click", (event) => { + toggleOptList(select); + }); - select.addEventListener("focus", (event) => { - activeSelect(select, selectList); - }); + select.addEventListener("focus", (event) => { + activeSelect(select, selectList); + }); - select.addEventListener("blur", (event) => { - deactivateSelect(select); - }); + select.addEventListener("blur", (event) => { + deactivateSelect(select); }); }); -window.addEventListener("load", () => { - const selectList = document.querySelectorAll(".select"); +const selectList = document.querySelectorAll(".select"); - selectList.forEach((select) => { - const optionList = select.querySelectorAll(".option"); - const selectedIndex = getIndex(select); +selectList.forEach((select) => { + const optionList = select.querySelectorAll(".option"); + const selectedIndex = getIndex(select); - select.tabIndex = 0; - select.previousElementSibling.tabIndex = -1; + select.tabIndex = 0; + select.previousElementSibling.tabIndex = -1; - updateValue(select, selectedIndex); + updateValue(select, selectedIndex); - optionList.forEach((option, index) => { - option.addEventListener("click", (event) => { - updateValue(select, index); - }); + optionList.forEach((option, index) => { + option.addEventListener("click", (event) => { + updateValue(select, index); }); + }); - select.addEventListener("keyup", (event) => { - let index = getIndex(select); - - if (event.key === "Escape") { - deactivateSelect(select); - } - if (event.key === "ArrowDown" && index < optionList.length - 1) { - index++; - } - if (event.key === "ArrowUp" && index > 0) { - index--; - } + select.addEventListener("keyup", (event) => { + let index = getIndex(select); - updateValue(select, index); - }); + if (event.key === "Escape") { + deactivateSelect(select); + } + if (event.key === "ArrowDown" && index < optionList.length - 1) { + index++; + } + if (event.key === "ArrowUp" && index > 0) { + index--; + } + + updateValue(select, index); }); }); ``` @@ -1903,62 +1883,58 @@ function getIndex(select) { return nativeWidget.selectedIndex; } -window.addEventListener("load", () => { - const form = document.querySelector("form"); +const form = document.querySelector("form"); - form.classList.remove("no-widget"); - form.classList.add("widget"); -}); +form.classList.remove("no-widget"); +form.classList.add("widget"); -window.addEventListener("load", () => { - const selectList = document.querySelectorAll(".select"); +const selectList = document.querySelectorAll(".select"); - selectList.forEach((select) => { - const optionList = select.querySelectorAll(".option"); - const selectedIndex = getIndex(select); - - select.tabIndex = 0; - select.previousElementSibling.tabIndex = -1; +selectList.forEach((select) => { + const optionList = select.querySelectorAll(".option"); + const selectedIndex = getIndex(select); - updateValue(select, selectedIndex); + select.tabIndex = 0; + select.previousElementSibling.tabIndex = -1; - optionList.forEach((option, index) => { - option.addEventListener("mouseover", () => { - highlightOption(select, option); - }); + updateValue(select, selectedIndex); - option.addEventListener("click", (event) => { - updateValue(select, index); - }); + optionList.forEach((option, index) => { + option.addEventListener("mouseover", () => { + highlightOption(select, option); }); - select.addEventListener("click", (event) => { - toggleOptList(select); + option.addEventListener("click", (event) => { + updateValue(select, index); }); + }); - select.addEventListener("focus", (event) => { - activeSelect(select, selectList); - }); + select.addEventListener("click", (event) => { + toggleOptList(select); + }); - select.addEventListener("blur", (event) => { - deactivateSelect(select); - }); + select.addEventListener("focus", (event) => { + activeSelect(select, selectList); + }); - select.addEventListener("keyup", (event) => { - let index = getIndex(select); + select.addEventListener("blur", (event) => { + deactivateSelect(select); + }); - if (event.key === "Escape") { - deactivateSelect(select); - } - if (event.key === "ArrowDown" && index < optionList.length - 1) { - index++; - } - if (event.key === "ArrowUp" && index > 0) { - index--; - } + select.addEventListener("keyup", (event) => { + let index = getIndex(select); - updateValue(select, index); - }); + if (event.key === "Escape") { + deactivateSelect(select); + } + if (event.key === "ArrowDown" && index < optionList.length - 1) { + index++; + } + if (event.key === "ArrowUp" && index > 0) { + index--; + } + + updateValue(select, index); }); }); ``` diff --git a/files/en-us/learn_web_development/extensions/forms/ui_pseudo-classes/index.md b/files/en-us/learn_web_development/extensions/forms/ui_pseudo-classes/index.md index eabeeb7c0347669..1d6d6f25e8f90c5 100644 --- a/files/en-us/learn_web_development/extensions/forms/ui_pseudo-classes/index.md +++ b/files/en-us/learn_web_development/extensions/forms/ui_pseudo-classes/index.md @@ -822,17 +822,10 @@ We've directly selected the inputs we want to disable using `input[type="text"]: Now finally, we've used some JavaScript to toggle the disabling of the billing address fields: ```js -// Wait for the page to finish loading -document.addEventListener( - "DOMContentLoaded", - () => { - // Attach `change` event listener to checkbox - document - .getElementById("billing-checkbox") - .addEventListener("change", toggleBilling); - }, - false, -); +// Attach `change` event listener to checkbox +document + .getElementById("billing-checkbox") + .addEventListener("change", toggleBilling); function toggleBilling() { // Select the billing text fields @@ -955,17 +948,10 @@ button { ``` ```js hidden live-sample___enabled-disabled-shipping -// Wait for the page to finish loading -document.addEventListener( - "DOMContentLoaded", - () => { - // Attach `change` event listener to checkbox - document - .getElementById("billing-checkbox") - .addEventListener("change", toggleBilling); - }, - false, -); +// Attach `change` event listener to checkbox +document + .getElementById("billing-checkbox") + .addEventListener("change", toggleBilling); function toggleBilling() { // Select the billing text fields diff --git a/files/en-us/web/accessibility/aria/reference/roles/tab_role/index.md b/files/en-us/web/accessibility/aria/reference/roles/tab_role/index.md index ec8484be7fc9336..2cb030f8364e1fb 100644 --- a/files/en-us/web/accessibility/aria/reference/roles/tab_role/index.md +++ b/files/en-us/web/accessibility/aria/reference/roles/tab_role/index.md @@ -161,43 +161,41 @@ To accomplish the first, we listen for the [`keydown`](/en-US/docs/Web/API/Eleme To handle changing the active `tab` and `tabpanel`, we have a function that takes in the event, gets the element that triggered the event, the triggering element's parent element, and its grandparent element. We then find all tabs with `aria-selected="true"` inside the parent element and sets it to `false`, then sets the triggering element's `aria-selected` to `true`. After that, we find all `tabpanel` elements in the grandparent element, make them all `hidden`, and finally select the element whose `id` is equal to the triggering `tab`'s `aria-controls` and removes the `hidden` attribute, making it visible. ```js -window.addEventListener("DOMContentLoaded", () => { - // Only handle one particular tablist; if you have multiple tab - // lists (might even be nested), you have to apply this code for each one - const tabList = document.querySelector('[role="tablist"]'); - const tabs = tabList.querySelectorAll(':scope > [role="tab"]'); - - // Add a click event handler to each tab - tabs.forEach((tab) => { - tab.addEventListener("click", changeTabs); - }); - - // Enable arrow navigation between tabs in the tab list - let tabFocus = 0; - - tabList.addEventListener("keydown", (e) => { - // Move right - if (e.key === "ArrowRight" || e.key === "ArrowLeft") { - tabs[tabFocus].setAttribute("tabindex", -1); - if (e.key === "ArrowRight") { - tabFocus++; - // If we're at the end, go to the start - if (tabFocus >= tabs.length) { - tabFocus = 0; - } - // Move left - } else if (e.key === "ArrowLeft") { - tabFocus--; - // If we're at the start, move to the end - if (tabFocus < 0) { - tabFocus = tabs.length - 1; - } - } +// Only handle one particular tablist; if you have multiple tab +// lists (might even be nested), you have to apply this code for each one +const tabList = document.querySelector('[role="tablist"]'); +const tabs = tabList.querySelectorAll(':scope > [role="tab"]'); + +// Add a click event handler to each tab +tabs.forEach((tab) => { + tab.addEventListener("click", changeTabs); +}); - tabs[tabFocus].setAttribute("tabindex", 0); - tabs[tabFocus].focus(); +// Enable arrow navigation between tabs in the tab list +let tabFocus = 0; + +tabList.addEventListener("keydown", (e) => { + // Move right + if (e.key === "ArrowRight" || e.key === "ArrowLeft") { + tabs[tabFocus].setAttribute("tabindex", -1); + if (e.key === "ArrowRight") { + tabFocus++; + // If we're at the end, go to the start + if (tabFocus >= tabs.length) { + tabFocus = 0; + } + // Move left + } else if (e.key === "ArrowLeft") { + tabFocus--; + // If we're at the start, move to the end + if (tabFocus < 0) { + tabFocus = tabs.length - 1; + } } - }); + + tabs[tabFocus].setAttribute("tabindex", 0); + tabs[tabFocus].focus(); + } }); function changeTabs(e) { diff --git a/files/en-us/web/api/canvas_api/tutorial/basic_usage/index.md b/files/en-us/web/api/canvas_api/tutorial/basic_usage/index.md index 40ce77a48a30f93..ea1d96141cb6c23 100644 --- a/files/en-us/web/api/canvas_api/tutorial/basic_usage/index.md +++ b/files/en-us/web/api/canvas_api/tutorial/basic_usage/index.md @@ -105,7 +105,7 @@ Here is a minimalistic template, which we'll be using as a starting point for la const ctx = canvas.getContext("2d"); } } - window.addEventListener("load", draw); + draw(); diff --git a/files/en-us/web/api/canvasrenderingcontext2d/globalcompositeoperation/index.md b/files/en-us/web/api/canvasrenderingcontext2d/globalcompositeoperation/index.md index 8a9605316fc3ea7..32ca074d9a4ea5f 100644 --- a/files/en-us/web/api/canvasrenderingcontext2d/globalcompositeoperation/index.md +++ b/files/en-us/web/api/canvasrenderingcontext2d/globalcompositeoperation/index.md @@ -178,22 +178,20 @@ const height = 340; When the page loads, this code runs to set up and run the example: ```js -window.onload = () => { - // lum in sRGB - const lum = { - r: 0.33, - g: 0.33, - b: 0.33, - }; - // resize canvas - canvas1.width = width; - canvas1.height = height; - canvas2.width = width; - canvas2.height = height; - lightMix(); - colorSphere(); - runComposite(); +// lum in sRGB +const lum = { + r: 0.33, + g: 0.33, + b: 0.33, }; +// resize canvas +canvas1.width = width; +canvas1.height = height; +canvas2.width = width; +canvas2.height = height; +lightMix(); +colorSphere(); +runComposite(); ``` And this code, `runComposite()`, handles the bulk of the work, relying on a number of utility functions to do the hard parts. diff --git a/files/en-us/web/api/customstateset/index.md b/files/en-us/web/api/customstateset/index.md index ea4ea427964a2bd..69e6b078eaeb8ba 100644 --- a/files/en-us/web/api/customstateset/index.md +++ b/files/en-us/web/api/customstateset/index.md @@ -153,17 +153,15 @@ class LabeledCheckbox extends HTMLElement { customElements.define("labeled-checkbox", LabeledCheckbox); // Display a warning to unsupported browsers -document.addEventListener("DOMContentLoaded", () => { - if (!LabeledCheckbox.isStateSyntaxSupported()) { - if (!document.getElementById("state-warning")) { - const warning = document.createElement("div"); - warning.id = "state-warning"; - warning.style.color = "red"; - warning.textContent = "This feature is not supported by your browser."; - document.body.insertBefore(warning, document.body.firstChild); - } +if (!LabeledCheckbox.isStateSyntaxSupported()) { + if (!document.getElementById("state-warning")) { + const warning = document.createElement("div"); + warning.id = "state-warning"; + warning.style.color = "red"; + warning.textContent = "This feature is not supported by your browser."; + document.body.insertBefore(warning, document.body.firstChild); } -}); +} ``` In the `LabeledCheckbox` class: @@ -270,17 +268,15 @@ class LabeledCheckbox extends HTMLElement { customElements.define("labeled-checkbox", LabeledCheckbox); -document.addEventListener("DOMContentLoaded", () => { - if (!LabeledCheckbox.isStateSyntaxSupported()) { - if (!document.getElementById("state-warning")) { - const warning = document.createElement("div"); - warning.id = "state-warning"; - warning.style.color = "red"; - warning.textContent = "This feature is not supported by your browser."; - document.body.insertBefore(warning, document.body.firstChild); - } +if (!LabeledCheckbox.isStateSyntaxSupported()) { + if (!document.getElementById("state-warning")) { + const warning = document.createElement("div"); + warning.id = "state-warning"; + warning.style.color = "red"; + warning.textContent = "This feature is not supported by your browser."; + document.body.insertBefore(warning, document.body.firstChild); } -}); +} ``` First, we define the custom element class `QuestionBox`, which extends `HTMLElement`. @@ -441,17 +437,15 @@ class ManyStateElement extends HTMLElement { customElements.define("many-state-element", ManyStateElement); -document.addEventListener("DOMContentLoaded", () => { - if (!LabeledCheckbox.isStateSyntaxSupported()) { - if (!document.getElementById("state-warning")) { - const warning = document.createElement("div"); - warning.id = "state-warning"; - warning.style.color = "red"; - warning.textContent = "This feature is not supported by your browser."; - document.body.insertBefore(warning, document.body.firstChild); - } +if (!LabeledCheckbox.isStateSyntaxSupported()) { + if (!document.getElementById("state-warning")) { + const warning = document.createElement("div"); + warning.id = "state-warning"; + warning.style.color = "red"; + warning.textContent = "This feature is not supported by your browser."; + document.body.insertBefore(warning, document.body.firstChild); } -}); +} ``` #### HTML diff --git a/files/en-us/web/api/datatransfer/cleardata/index.md b/files/en-us/web/api/datatransfer/cleardata/index.md index 20e623077775dee..c3f7d1b7beab534 100644 --- a/files/en-us/web/api/datatransfer/cleardata/index.md +++ b/files/en-us/web/api/datatransfer/cleardata/index.md @@ -82,90 +82,87 @@ span.tweaked { ### JavaScript ```js -window.addEventListener("DOMContentLoaded", () => { - // Select HTML elements - const draggable = document.getElementById("source"); - const droppable = document.getElementById("target"); - const status = document.getElementById("status"); - const data = document.getElementById("data"); - let dropped = false; +// Select HTML elements +const draggable = document.getElementById("source"); +const droppable = document.getElementById("target"); +const status = document.getElementById("status"); +const data = document.getElementById("data"); +let dropped = false; - // Register event handlers - draggable.addEventListener("dragstart", dragStartHandler); - draggable.addEventListener("dragend", dragEndHandler); - droppable.addEventListener("dragover", dragOverHandler); - droppable.addEventListener("dragleave", dragLeaveHandler); - droppable.addEventListener("drop", dropHandler); +// Register event handlers +draggable.addEventListener("dragstart", dragStartHandler); +draggable.addEventListener("dragend", dragEndHandler); +droppable.addEventListener("dragover", dragOverHandler); +droppable.addEventListener("dragleave", dragLeaveHandler); +droppable.addEventListener("drop", dropHandler); - function dragStartHandler(event) { - status.textContent = "Drag in process"; +function dragStartHandler(event) { + status.textContent = "Drag in process"; - // Change target element's border to signify drag has started - event.currentTarget.style.border = "1px dashed blue"; + // Change target element's border to signify drag has started + event.currentTarget.style.border = "1px dashed blue"; - // Start by clearing existing clipboards; this will affect all types since we - // don't give a specific type. + // Start by clearing existing clipboards; this will affect all types since we + // don't give a specific type. - event.dataTransfer.clearData(); + event.dataTransfer.clearData(); - // Set the drag's format and data (use event target's id for data) - event.dataTransfer.setData("text/plain", event.target.id); + // Set the drag's format and data (use event target's id for data) + event.dataTransfer.setData("text/plain", event.target.id); - data.textContent = event.dataTransfer.getData("text/plain"); - } + data.textContent = event.dataTransfer.getData("text/plain"); +} - function dragEndHandler(event) { - if (!dropped) { - status.textContent = "Drag canceled"; - } +function dragEndHandler(event) { + if (!dropped) { + status.textContent = "Drag canceled"; + } - data.textContent = event.dataTransfer.getData("text/plain") || "empty"; + data.textContent = event.dataTransfer.getData("text/plain") || "empty"; - // Change border to signify drag is no longer in process - event.currentTarget.style.border = "1px solid black"; + // Change border to signify drag is no longer in process + event.currentTarget.style.border = "1px solid black"; - if (dropped) { - // Remove all event listeners - draggable.removeEventListener("dragstart", dragStartHandler); - draggable.removeEventListener("dragend", dragEndHandler); - droppable.removeEventListener("dragover", dragOverHandler); - droppable.removeEventListener("dragleave", dragLeaveHandler); - droppable.removeEventListener("drop", dropHandler); - } + if (dropped) { + // Remove all event listeners + draggable.removeEventListener("dragstart", dragStartHandler); + draggable.removeEventListener("dragend", dragEndHandler); + droppable.removeEventListener("dragover", dragOverHandler); + droppable.removeEventListener("dragleave", dragLeaveHandler); + droppable.removeEventListener("drop", dropHandler); } +} - function dragOverHandler(event) { - status.textContent = "Drop available"; +function dragOverHandler(event) { + status.textContent = "Drop available"; - event.preventDefault(); - } + event.preventDefault(); +} - function dragLeaveHandler(event) { - status.textContent = "Drag in process (drop was available)"; +function dragLeaveHandler(event) { + status.textContent = "Drag in process (drop was available)"; - event.preventDefault(); - } + event.preventDefault(); +} - function dropHandler(event) { - dropped = true; +function dropHandler(event) { + dropped = true; - status.textContent = "Drop done"; + status.textContent = "Drop done"; - event.preventDefault(); + event.preventDefault(); - // Get data linked to event format « text » - const _data = event.dataTransfer.getData("text/plain"); - const element = document.getElementById(_data); + // Get data linked to event format « text » + const _data = event.dataTransfer.getData("text/plain"); + const element = document.getElementById(_data); - // Append drag source element to event's target element - event.target.appendChild(element); + // Append drag source element to event's target element + event.target.appendChild(element); - // Change CSS styles and displayed text - element.style.cssText = - "border: 1px solid black;display: block; color: red"; - element.textContent = "I'm in the Drop Zone!"; - } -}); + // Change CSS styles and displayed text + element.style.cssText = "border: 1px solid black;display: block; color: red"; + element.textContent = "I'm in the Drop Zone!"; +} ``` {{EmbedLiveSample('Examples', 300, 300)}} diff --git a/files/en-us/web/api/document/createelement/index.md b/files/en-us/web/api/document/createelement/index.md index 96203a38a2d5189..2f6a15d063ab722 100644 --- a/files/en-us/web/api/document/createelement/index.md +++ b/files/en-us/web/api/document/createelement/index.md @@ -58,8 +58,6 @@ This creates a new `
` and inserts it before the element with the ID `div1`. #### JavaScript ```js -document.body.onload = addElement; - function addElement() { // create a new div element const newDiv = document.createElement("div"); @@ -74,6 +72,8 @@ function addElement() { const currentDiv = document.getElementById("div1"); document.body.insertBefore(newDiv, currentDiv); } + +addElement(); ``` #### Result diff --git a/files/en-us/web/api/document/domcontentloaded_event/index.md b/files/en-us/web/api/document/domcontentloaded_event/index.md index 3b07845cda9e75c..a0b7216235296b4 100644 --- a/files/en-us/web/api/document/domcontentloaded_event/index.md +++ b/files/en-us/web/api/document/domcontentloaded_event/index.md @@ -14,6 +14,8 @@ The **`DOMContentLoaded`** event fires when the HTML document has been completel A different event, {{domxref("Window/load_event", "load")}}, should be used only to detect a fully-loaded page. It is a common mistake to use `load` where `DOMContentLoaded` would be more appropriate. +Usually, to avoid running a script before the DOM it manipulates has been fully constructed, you can simply place the script at the end of the document body, immediately before the closing `` tag, without wrapping it in an event listener. + This event is not cancelable. ## Syntax diff --git a/files/en-us/web/api/document_object_model/examples/index.md b/files/en-us/web/api/document_object_model/examples/index.md index c4aac6122a52bdf..48be9a08abdad34 100644 --- a/files/en-us/web/api/document_object_model/examples/index.md +++ b/files/en-us/web/api/document_object_model/examples/index.md @@ -327,9 +327,7 @@ function showEventProperties(e) { document.body.appendChild(table); } -window.onload = (event) => { - showEventProperties(event); -}; +showEventProperties(event); ``` {{EmbedLiveSample("example_7_displaying_event_object_properties", "", "300")}} diff --git a/files/en-us/web/api/document_object_model/introduction/index.md b/files/en-us/web/api/document_object_model/introduction/index.md index ef3017140be24e8..83868e9274fe534 100644 --- a/files/en-us/web/api/document_object_model/introduction/index.md +++ b/files/en-us/web/api/document_object_model/introduction/index.md @@ -88,19 +88,16 @@ and then adds it to the tree for the document: ```html - + + - - + ``` diff --git a/files/en-us/web/api/event/eventphase/index.md b/files/en-us/web/api/event/eventphase/index.md index c99c6d83c05556a..b353e32dd8f719c 100644 --- a/files/en-us/web/api/event/eventphase/index.md +++ b/files/en-us/web/api/event/eventphase/index.md @@ -88,22 +88,17 @@ div { ```js let clear = false; -let divInfo = null; -let divs = null; -let chCapture = null; - -window.onload = () => { - divInfo = document.getElementById("divInfo"); - divs = document.getElementsByTagName("div"); - chCapture = document.getElementById("chCapture"); - chCapture.onclick = () => { - removeListeners(); - addListeners(); - clearDivs(); - }; - clearDivs(); +const divInfo = document.getElementById("divInfo"); +const divs = document.getElementsByTagName("div"); +const chCapture = document.getElementById("chCapture"); + +chCapture.addEventListener("click", () => { + removeListeners(); addListeners(); -}; + clearDivs(); +}); +clearDivs(); +addListeners(); function removeListeners() { for (const div of divs) { diff --git a/files/en-us/web/api/file_api/using_files_from_web_applications/index.md b/files/en-us/web/api/file_api/using_files_from_web_applications/index.md index dd0e750b48d5fb6..7a039d57f3d20a1 100644 --- a/files/en-us/web/api/file_api/using_files_from_web_applications/index.md +++ b/files/en-us/web/api/file_api/using_files_from_web_applications/index.md @@ -476,6 +476,15 @@ if (isset($_FILES["myFile"])) { dnd binary upload + + +
+
+ Drag & drop your file here +
+
- - -
-
- Drag & drop your file here -
-
``` diff --git a/files/en-us/web/api/hid/getdevices/index.md b/files/en-us/web/api/hid/getdevices/index.md index 02bad698d4f1671..73db5808364d02f 100644 --- a/files/en-us/web/api/hid/getdevices/index.md +++ b/files/en-us/web/api/hid/getdevices/index.md @@ -31,11 +31,9 @@ A {{jsxref("Promise")}} that resolves with a list of {{domxref("HIDDevice")}} ob The following example gets a list of devices and logs the device names to the console. ```js -document.addEventListener("DOMContentLoaded", async () => { - let devices = await navigator.hid.getDevices(); - devices.forEach((device) => { - console.log(`HID: ${device.productName}`); - }); +let devices = await navigator.hid.getDevices(); +devices.forEach((device) => { + console.log(`HID: ${device.productName}`); }); ``` diff --git a/files/en-us/web/api/hiddevice/opened/index.md b/files/en-us/web/api/hiddevice/opened/index.md index 14ab4545fd4507d..c210d2ef6f3a70f 100644 --- a/files/en-us/web/api/hiddevice/opened/index.md +++ b/files/en-us/web/api/hiddevice/opened/index.md @@ -21,11 +21,9 @@ A boolean value, true if the connection is open. The following example retrieves devices with {{domxref("HID.getDevices()")}} and logs the value of `opened` to the console. ```js -document.addEventListener("DOMContentLoaded", async () => { - let devices = await navigator.hid.getDevices(); - devices.forEach((device) => { - console.log(`HID: ${device.opened}`); - }); +let devices = await navigator.hid.getDevices(); +devices.forEach((device) => { + console.log(`HID: ${device.opened}`); }); ``` diff --git a/files/en-us/web/api/hiddevice/productid/index.md b/files/en-us/web/api/hiddevice/productid/index.md index 2e4ce3cf6bce603..ac5badc73cb7de4 100644 --- a/files/en-us/web/api/hiddevice/productid/index.md +++ b/files/en-us/web/api/hiddevice/productid/index.md @@ -21,11 +21,9 @@ An integer. If the device has no product ID, or the product ID cannot be accesse The following example retrieves devices with {{domxref("HID.getDevices()")}} and logs the value of `productId` to the console. ```js -document.addEventListener("DOMContentLoaded", async () => { - let devices = await navigator.hid.getDevices(); - devices.forEach((device) => { - console.log(`HID: ${device.productId}`); - }); +let devices = await navigator.hid.getDevices(); +devices.forEach((device) => { + console.log(`HID: ${device.productId}`); }); ``` diff --git a/files/en-us/web/api/hiddevice/productname/index.md b/files/en-us/web/api/hiddevice/productname/index.md index 88eb9df5ca2002b..e26b4375533ec5f 100644 --- a/files/en-us/web/api/hiddevice/productname/index.md +++ b/files/en-us/web/api/hiddevice/productname/index.md @@ -21,11 +21,9 @@ A string. The following example retrieves devices with {{domxref("HID.getDevices()")}} and logs the value of `productName` to the console. ```js -document.addEventListener("DOMContentLoaded", async () => { - let devices = await navigator.hid.getDevices(); - devices.forEach((device) => { - console.log(`HID: ${device.productName}`); - }); +let devices = await navigator.hid.getDevices(); +devices.forEach((device) => { + console.log(`HID: ${device.productName}`); }); ``` diff --git a/files/en-us/web/api/hiddevice/vendorid/index.md b/files/en-us/web/api/hiddevice/vendorid/index.md index eb2ef3e589b541d..3926fabb5a32a28 100644 --- a/files/en-us/web/api/hiddevice/vendorid/index.md +++ b/files/en-us/web/api/hiddevice/vendorid/index.md @@ -21,11 +21,9 @@ An integer. If the device has no vendor ID, or the vendor ID cannot be accessed The following example retrieves devices with {{domxref("HID.getDevices()")}} and logs the value of `vendorId` to the console. ```js -document.addEventListener("DOMContentLoaded", async () => { - let devices = await navigator.hid.getDevices(); - devices.forEach((device) => { - console.log(`HID: ${device.vendorId}`); - }); +let devices = await navigator.hid.getDevices(); +devices.forEach((device) => { + console.log(`HID: ${device.vendorId}`); }); ``` diff --git a/files/en-us/web/api/htmlbuttonelement/labels/index.md b/files/en-us/web/api/htmlbuttonelement/labels/index.md index 9b419cad0fc85d0..2c3b1e3acd9b7ff 100644 --- a/files/en-us/web/api/htmlbuttonelement/labels/index.md +++ b/files/en-us/web/api/htmlbuttonelement/labels/index.md @@ -30,12 +30,10 @@ with the `