rob.m rob.m - 1 month ago 9
Javascript Question

Add class on click to a path with leaflet js

I am trying to add a class to the clicked polygon using:

function addClass() {
function style(feature) {
return {
className: "active"
};
}
}

function onEachFeature(feature, layer) {
layer.on({
click: addClass
});
}


codepen

Docs here

Answer

The function app in your code only creates a function (and nothing more). This function is only created, but never fired. Another problem is that this function does nothing that relevant to the element that was clicked.

Here is the change you are looking for:

function app(e) {
    this.getElement().classList.add('active')
}

Here is a working codepen (based on your code):
http://codepen.io/anon/pen/pEmMRE

I added the active class to the CSS so you can actually see the change on the screen