How can I pass a parameter to a function without it running right away?

Have showArea return a function that works with the id.

function showArea(id) {
   return function() {
       // do stuff with id
   };
}

The returned function closes over id so it continues to reference it, and is passed to addListener to be used as the handler.


Alternately, you could just inline the function that calls showArea(1)

google.maps.event.addListener(southEast, 'click', function() { showArea(1); });
function showArea(id) {
   // do stuff based on that id
}

This will work because you’re hardcoding the 1. If it was a variable that could change, like in a loop, you’d use the first example.

Leave a Comment