Skip to content Skip to sidebar Skip to footer

Why Is My Click Function Not Working As Expected?

I've created a simple js project which plots a series of points using leaflet.js. I then want to populate an info window with point specific data with an on click event. But I can'

Solution 1:

On this line:

.on('click', fill_info_window(data, i));

...you're calling the fill_info_window function, not just referring to it. You want to do something like this:

.on('click', function() {
    fill_info_window(data, i);
});

unless you're in a loop (that i variable makes me think maybe you are). If you are, then:

.on('click', makeHandler(data, i));

...where makeHandler looks like this:

function makeHandler(theData, index) {
    return function() {
        fill_info_window(theData, index);
    };
}

The reason you don't want my first answer in a loop is that all of the handlers will refer to the same data and i variables, and see their value as of when the handler is called, not when it's registered. That's why we use the makeHandler function instead, so it creates a closure over something that doesn't change. More on my blog: Closures are not complicated


Solution 2:

You probably want to bind the function as a handler, not its result from calling it. So remove the invocation and use ….on('click', fill_info_window);. See also this quirksmode article about event handling: No parenthesis!.


Post a Comment for "Why Is My Click Function Not Working As Expected?"