[Solved] Why is my click function not working as expected?


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

2

solved Why is my click function not working as expected?