Home > Mobile >  Ways to wait for elements to load when adding eventlisteners
Ways to wait for elements to load when adding eventlisteners

Time:11-24

I'm playing around with parcel before I used liveserver in vscode and I rarely ran into this problem. I'm trying to add a eventlistener to a inputform. DOM isn't finding the element no matter what I do. I've tried to put a if statement checking if the element exist before putting a listener but it doesn't change anything. I never had this problem using liveserver, do i have to write a asynchronous function and wait for the page to load? I tried putting defer inside the script tag aswell. Is parcel slower than liveserver somehow?

const input1 = document.getElementById("input1");
if(input1)
{
    console.log("The input exists");
    input1.addEventListener('click', () =>{
        console.log("heey");
    });
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./assets/scss/main.scss">
</head>

<body>
    <form>
        <div >
            <label for="inputlg">input</label>
            <input  id="inputlg" type="text" id="input1">
            <label for="inputlg">output</label>
            <input  id="inputlg" type="text">
        </div>

    </form>
    <script type="module" src="./assets/js/main.js" ></script>
</body>

</html>

CodePudding user response:

Your input has two ids. That's invalid, and getElementById doesn't see the second one.

const input1 = document.getElementById('input1');
console.log(input1); // null

const inputlg = document.getElementById('inputlg');
console.log(inputlg); // input#inputlg.form-control.input-lg
<input  id="inputlg" type="text" id="input1">

CodePudding user response:

There are a few ways.

  1. (best) document.addEventListener('DOMContentLoaded', () => { // code here })
  2. document.onreadystatechange = () => { if (document.readystate == "complete") { // code here } }

Also, it is a requirement that there is only 1 element assigned to each ID. In your code, you have 2 elements with ID "inputlg", which is not allowed. Get rid of those and it should work. You also have an element which you are trying to have 2 IDs on, which also does not work.

The code above is just to make sure that the document is fully loaded, and prevents errors.

  • Related