fix: initialize DOM elements only when executing methods/in pages that

contain those elements

SUMMARY
    Trying to grab elements globally in a script results in it trying to
    initialize in all pages. When the element is absent, the script
    fails and JavaScript crashes.
This commit is contained in:
realaravinth
2022-07-23 00:48:15 +05:30
parent b12c30e956
commit b6afe79a81
3 changed files with 20 additions and 12 deletions

View File

@@ -30,14 +30,6 @@ export const FORM = <HTMLFormElement>(
document.querySelector(`.${SITE_KEY_FORM_CLASS}`)
);
export const AVG_TRAFFIC = <HTMLInputElement>FORM.querySelector("#avg_traffic");
export const PEAK_TRAFFIC = <HTMLInputElement>(
FORM.querySelector("#peak_sustainable_traffic")
);
export const BROKE_MY_SITE_TRAFFIC = <HTMLInputElement>(
FORM.querySelector("#broke_my_site_traffic")
);
export const addSubmitEventListener = (): void =>
FORM.addEventListener("submit", submit, true);
@@ -57,6 +49,16 @@ export const validate = (e: Event): TrafficPattern => {
let broke_is_set = false;
const AVG_TRAFFIC = <HTMLInputElement>(
FORM.querySelector("#avg_traffic")
);
const PEAK_TRAFFIC = <HTMLInputElement>(
FORM.querySelector("#peak_sustainable_traffic")
);
const BROKE_MY_SITE_TRAFFIC = <HTMLInputElement>(
FORM.querySelector("#broke_my_site_traffic")
);
isBlankString(AVG_TRAFFIC.value, avg_traffic_name);
isBlankString(PEAK_TRAFFIC.value, peak_traffic_name);

View File

@@ -25,10 +25,10 @@ import { validate, FORM } from "../../add/novice/ts/form";
const SUBMIT_BTN = <HTMLButtonElement>(
document.querySelector(".sitekey-form__submit")
);
const key = SUBMIT_BTN.dataset.sitekey;
const submit = async (e: Event) => {
e.preventDefault();
const key = SUBMIT_BTN.dataset.sitekey;
const formUrl = getFormUrl(FORM);
const payload = {
pattern: validate(e),