0

Im learning JS and working with passing variables between functions. I am trying to execute a function on click whilst passing a variable between functions. I can pass the variable by executing the function on page load, but cant do it on a click function.

function getData() {
    let xmlhttp = new XMLHttpRequest();
    let url = "https://jsonplaceholder.typicode.com/posts";
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            myArr = JSON.parse(this.responseText);
            //myFunction(myArr); 
            document.getElementById("start2").addEventListener("click", myFunction(myArr));
        }
    };
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}

getData();


function myFunction(arr) {
    //  var arr = getData();
    var out = "";
    var i;
    for (i = 0; i < arr.length; i++) {
        out += '<p>' + arr[i].id + '</p><br>';
    }
    document.getElementById("answer-holder").innerHTML = out;
}

2 Answers 2

1

It does not work, since addEventListener expects a function as its second argument. But you do not provide a function. Instead you provide the result of evaluating myFunction, which is undefined (since myFunction does not return anything).

// when `addEventListener` is called, `myFunction` is also called immediately, 
// instead of first being called when the event is triggered 
document.getElementById("start2").addEventListener("click", myFunction(myArr));

You can fix the code by instead providing a function, that calls myFunction with your chosen argument.

document.getElementById("start2").addEventListener("click", function() {
   myFunction(myArr);
});
Sign up to request clarification or add additional context in comments.

2 Comments

That is awesome, great answer and thanks for the explanation as that helps me to learn. Cheers
@insomniac22 No problem, happy to help!
0

The problem is you are calling the function when trying to set the onClick listener:

document.getElementById("start2").addEventListener("click", myFunction(myArr));

As suggested by Thomas, you have to pass a function to addEventListener. However, I would suggest the newer lambda notation:

document.getElementById("start2").addEventListener("click", () => myFunction(myArr));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.