Some functions automatically executing

Hello! I’m working on a project where I need to hide an element until a button is clicked. I’m doing this by toggling a ‘hidden’ class on the element. However, the toggle function appears to be automatically executing when it is declared and I can’t figure out why. Here’s my code so far:

const goBtn = document.getElementById('go-btn');
const topTxtInput = document.getElementById('top-text-input');
const btmTxtInput = document.getElementById('btm-text-input');
const imgUrl = document.getElementById('img-input');
const result = document.getElementById('result');
const gallery = document.getElementById('gallery');
const keep = document.getElementById('keep-img');
const discard = document.getElementById('discard-img');

//Functions:
function toggleResult() {
    const resultBox = document.getElementById('result-div');
    resultBox.classList.toggle("hidden");
}

function generateMeme(img, top, btm) {
    if (result.classList.contains("current")) {
        return;
    } else {
        result.classList.add("current");
        result.innerHTML += `
        <div class="current-meme" style="background-image: url(${img})">
            <p class="top">${top}</p>
            <p class="btm">${btm}</p>
        </div>`;
        toggleResult();
    } 
}

function reset() {
    result.classList.remove("current");
    result.innerHTML = "";
    topTxtInput.value = "";
    btmTxtInput.value = "";
    toggleResult();
}

function addToGallery() {
    gallery.innerHTML += result.innerHTML;
    reset();
}

 
//Event listeners:
keep.addEventListener('click', addToGallery);
discard.addEventListener('click', reset)
goBtn.addEventListener('click', generateMeme(imgUrl.value, topTxtInput.value, btmTxtInput.value))
goBtn.addEventListener('submit', (e) => {e.preventDefault()})

The toggleResult and generateMeme functions are automatically executing, while the other functions are not. Have I messed up the syntax? Missed a semi-colon? Totally pulling my hair out!

You should be passing a callback function to your addEventListener, but instead you are immediately invoking it

generateMeme(imgUrl.value, topTxtInput.value, btmTxtInput.value)

This is the syntax for calling a function with those parameters. To pass a callback function you need to not use the parantheses ( ).

Then, inside your generateMeme function you also invoke your toggle result function:

toggleResult()

Since you have just called generateMeme, it will be also be invoked.

The best way around this in your particular case would be to define a callBack function that simply calls your generateMeme function when it is called, and pass that as the callback function to addEventListener. You can do that inline with the arrow syntax

(..."click", () => {
  generateMeme(...);
}
1 Like