Wait for DOM loading template literals

248 Views Asked by At

I am working on a project for a SPA using hash and vanilla JS. I am injecting html content with a js file but when I am trying to select elements from the DOM it seems like my function runs before the DOM is fully loaded and returns null. I have tried: window.onload, DOMContentLoaded, stateChange.

But it only works the way I want to when I do a setTimeOut which seems a little hacky.

Is there another way to have this working? My JS function writing on the DOM is async, I'm not sure how to do the await for it if that's how it is supposed to be fixed

    const getRandomDrink = () => {
    let randomDrinkBtn = document.getElementById("random-drink")
    console.log(randomDrinkBtn)
    randomDrinkBtn.addEventListener('click', ()=>{
        location.hash = "/random.php"
    })
}
window.onload = getRandomDrink // Does not work
setTimeOut(() => {getRandomDrink()}, 1000) This works

This is the JS file, adding elements to the DOM. I apologize, since I don't know how to replicate the issue with all the different files.

const Home = async () => {
    let ingArgument = "list.php?i=list" 
    ingArgument.replace(/['"]+/g, '')
    const content = await getData(ingArgument) // This displays ingredients from the API, not related to the issue I am having
    const view = `
        <section class="Section-main">
            <h1>A New Way Of Making Cocktails</h1>
            <button id="random-drink">
                Get A Recipe Now</button>
        </section>
    `
    return view
}

edit I ended up just adding the listener in the same file like suggested by @Taplar below.

<button id="random-drink" onclick="location.hash = '/random.php'">
0

There are 0 best solutions below