Astronaut
Astronaut

Reputation: 7051

Passing parameters to window.addEventListener function

I am trying to pass parameters to a function using

window.addEventListener('resize', writeMSG(X, Y));

function writeMSG(x, y){
    console.log("Resize Event"+x+":"+y);
}

However this dos not work the event is trigerred only once. If I use just the function name, this calls the function correctly on resize event but I don't have the parameters, (I don't want to put them on global):

window.addEventListener('resize', writeMSG);

Inside the functon I have the event object... Do I have to pass the parameters inside the event object? Grab the event object and attach the parameters, or is there a better way of doing this?

Upvotes: 1

Views: 1885

Answers (1)

jfriend00
jfriend00

Reputation: 708156

You can add a function stub to call your function when the event fires:

window.addEventListener('resize', function(e) {
    writeMSG(X, Y);
});

The way you were trying to do it, you were calling writeMSG() immediately and passing its return value to addEventListener() which was certainly not what you wanted (that's why it was only getting called once).

Upvotes: 7

Related Questions