1

I have 10 html files that require JS functions to run, all JS is in one script.

JS file will run top to bottom. If HTML file1 has its function(s) at the top of the JS file, it will all run fine and do what it should do. If HTML file2 has its function(s) further down in the JS file, the functions will not run and I will get a 'Cannot read property 'addEventListener' of null' error because the JS is looking for the top function and references in HTML file2 but it isn't there, therefore it won't continue to where the function is (ie further down the list in the JS script file)

Problem is the top function in JS file will run first, if it can't find the first function or references in the HTML file then I will get a 'Cannot read property 'addEventListener' of null' error because the item is not there.

What am I doing wrong and what works better?

Thanks for you help

JS

// ** COOKIE POLICY **
//Expand All
const cp_exin_expandAll = document.getElementById('cp_exin_expandAll');

cp_exin_expandAll.addEventListener('click', () => {
    // const buttons = document.querySelectorAll('.cookiepolicy_extrainfo_column');
    const cp_exin_content = document.querySelectorAll(".cookiepolicy_extrainfo_content");
    for (let i = 0; i < cp_exin_content.length; i++) {
        cp_exin_content[i].classList.remove('show-individual');
        cp_exin_content[i].classList.toggle('show');
    };
});

//Collapse Individual Points
const banner = document.querySelector('.cookiepolicy_extrainfo_banner');

banner.addEventListener('click', (e) => {
    const cp_exin_col = document.querySelectorAll(".cookiepolicy_extrainfo_column");
    const cp_exin_content = document.querySelectorAll(".cookiepolicy_extrainfo_content");
    for (let i = 0; i < cp_exin_col.length; i++) {
        if (e.target === cp_exin_col[i]) {
            cp_exin_content[i].classList.toggle('show-individual');
        }
    };
});

// ** BUSINESS CONTACT US ** - Form input error
var businessForm = document.getElementById('businesscontactus_form');
const companyName = document.getElementById('companyName');
const businessRepName = document.getElementById('businessRepName');
const companyPosition = document.getElementById('companyPosition');
const businessEmail = document.getElementById('businessEmail');
const businessMessage = document.getElementById('businessMessage');

businessForm.addEventListener('submit', e => {
    e.preventDefault();

    checkInputs();
});

function checkInputs() {
    // trim to remove the whitespaces
    const companyNameValue = companyName.value.trim();
    const businessRepNameValue = businessRepName.value.trim();
    const companyPositionValue = companyPosition.value.trim();
    const businessEmailValue = businessEmail.value.trim();
    const businessMessageValue = businessMessage.value.trim();

    if (companyNameValue === '') {
        setErrorFor(companyName, 'Company Name must be entered');
    } else {
        setSuccessFor(companyName);
    };

    if (businessRepNameValue === '') {
        setErrorFor(businessRepName, 'Name cannot be blank');
    } else {
        setSuccessFor(businessRepName);
    };

    if (businessEmailValue === '') {
        setErrorFor(businessEmail, 'Email cannot be blank');
    } else if (!isEmail(businessEmailValue)) {
        setErrorFor(businessEmail, 'Not a valid email');
    } else {
        setSuccessFor(businessEmail);
    };

    if (companyPositionValue === '') {
        setErrorFor(companyPosition, 'Company position cannot be blank');
    } else {
        setSuccessFor(companyPosition);
    };

    if (businessMessageValue === '') {
        setErrorFor(businessMessage, 'Message cannot be blank');
    } else {
        setSuccessFor(businessMessage);
    };
};

function setErrorFor(input, message) {
    const formControl = input.parentElement;
    const small = formControl.querySelector('small');
    formControl.className = 'business-form-control error';
    small.innerText = message;
};

function setSuccessFor(input) {
    const formControl = input.parentElement;
    formControl.className = 'business-form-control success';
};

function isEmail(businessEmail) {
    return /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(businessEmail);
};

// ** CUSTOMER CONTACT US ** 
const customer_contactus_form = document.getElementById('customercontactus_form');
const customerCUName = document.getElementById('customerCUName');
const customerCUSubject = document.getElementById('customerCUSubject');
const customerCUEmail = document.getElementById('customerCUEmail');
const customerCUMessage = document.getElementById("customerCUMessage");
const customerCUDisclaimerBox = document.getElementById('customerCUDisclaimerBox');

customer_contactus_form.addEventListener('submit', e => {
    e.preventDefault();

    checkcustomerCU_Inputs();
});

function checkcustomerCU_Inputs() {
    //trim to remove the whitespaces
    const customerCUNameValue = customerCUName.value.trim();
    const customerCUSubjectValue = customerCUSubject.value.trim();
    const customerCUEmailValue = customerCUEmail.value.trim();
    const customerCUMessageValue = customerCUMessage.value.trim();

    if (customerCUNameValue === '') {
        setErrorForCU(customerCUName, 'Please enter your name');
    } else {
        setSuccessForCU(customerCUName);
    };

    if (customerCUSubjectValue === '') {
        setErrorForCU(customerCUSubject, 'Please enter a subject in order for us to help you better.');
    } else {
        setSuccessForCU(customerCUSubject);
    };

    if (customerCUEmailValue === '') {
        setErrorForCU(customerCUEmail, 'Email cannot be blank');
    } else if (!isEmail(customerCUEmailValue)) {
        setErrorForCU(customerCUEmail, 'Not a valid email');
    } else {
        setSuccessForCU(customerCUEmail);
    };

    if (customerCUMessageValue === '') {
        setErrorForCU(customerCUMessage, 'Please enter a message.');
    } else {
        setSuccessForCU(customerCUMessage);
    };

    if (!customerCUDisclaimerBox.checked) {
        setErrorForCU(customerCUDisclaimerBox, 'Please check box and accept terms and conditions.');
    } else {
        setSuccessForCU(customerCUDisclaimerBox);
    };
};

function setErrorForCU(input, message) {
    const formControlCU = input.parentElement;
    const small = formControlCU.querySelector('small');
    formControlCU.className = 'customer-form-control error';
    small.innerText = message;
};

function setSuccessForCU(input) {
    const formControl = input.parentElement;
    formControl.className = 'customer-form-control success';
};

function isEmailCU(customerCUEmail) {
    return /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(customerCUEmail);
};

Errors being returned:

Refused to apply style from 'http://127.0.0.1:5501/Website/css/fontawesome/all.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
customercontactus.html:1 Refused to apply style from 'http://127.0.0.1:5501/Website/css/fontawesome/all.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
script.js:5 Uncaught TypeError: Cannot read property 'addEventListener' of null
    at script.js:5
  • Why are you including the same JavaScript file twice. What is it doing? Do you realize that when you define the same function twice it just overrides, they are not two instances of the function/variable.. – epascarello Mar 17 '21 at 13:51
  • I'm new to this and I was told put it at the top and bottom so it works. Where should I insert the Script src, top or bottom or the HTML? – Adam Lansome Mar 17 '21 at 13:54
  • 1
    You likely have an error somewhere, or something returning unexpected undefined or null causing the execution to the halted. And, only include the code once. – Joe DF Mar 17 '21 at 13:55
  • 1
    You are referencing elements in your code. When you put the script at the top of the page, you reference the element before it exists. When you move it to the bottom the element exists. https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element So at the top, when you are trying to add an event to an element, you get an error. Remove the top script... – epascarello Mar 17 '21 at 13:56
  • Ok I deleted the top script and kept with the bottom one on all the HTML files. Still running into the same problem – Adam Lansome Mar 17 '21 at 14:09
  • @JoeDF - I've pasted the errors I'm getting on the question above. If I move the function that uses the font-awesome to the top of the JS file it works perfectly fine – Adam Lansome Mar 17 '21 at 14:12
  • `Cannot read property 'addEventListener' of null` – epascarello Mar 17 '21 at 14:13
  • Ok I figured out what its doing. – Adam Lansome Mar 17 '21 at 14:26
  • It seems to be going throough the JS file Top to bottom. If HTML 1 has the top function (expand all) it will run. When I try to run HTML 2, it will give me an error as HTML doesn't have the top function (expand all) - hope that makes sense. How do I get the HTML file to run the JS that it needs for only that file and not try to match all the JS to that file – Adam Lansome Mar 17 '21 at 14:31
  • Hope I'm making sense here – Adam Lansome Mar 17 '21 at 14:31

1 Answers1

1

Try to cover addEventListener parts with if statement like below

const cp_exin_expandAll = document.getElementById('cp_exin_expandAll');
if(cp_exin_expandAll != null) {
    cp_exin_expandAll.addEventListener('click', () => {
        const cp_exin_content = document.querySelectorAll(".cookiepolicy_extrainfo_content");
        for (let i = 0; i < cp_exin_content.length; i++) {
            cp_exin_content[i].classList.remove('show-individual');
            cp_exin_content[i].classList.toggle('show');
        };
    });
}
Jejun
  • 357
  • 1
  • 12