I have a layer from a CartoDB viz that I’m listening to the featureclick event. When a feature is clicked I highlight it by applying cartoCss. However, I want to unhighlight it when I click on an area of map with no feature. I did this using the Leaflet map.on(‘preclick’) event. I chose preclick so it fires before the featureclick and applies the default cartoCss first.

Problem is the two events don’t play nicely. The map click event always fires, but the layer featureclick event only fires some of the time. So it sometimes takes two or three clicks before the feature is highlighted – even when the cursor has changed to a pointer so the map knows there is a feature there.

What is the best way to unhighlight a feature after a mouse click on the basemap?

Can I ignore my map click event when a layer feature is clicked?

Can I change which event fires first i.e. layer featureclick before map click?


   map.on('preclick', function(e) {
          //remove project highlighting and close popup

layer.getSubLayer(0).on('featureClick', function(e, latLong, pos, data, layerIndex) {

   highlightProject : function(projectName) {
          //Update the style


1 Answer 1


A simple solution would be to only utilize the leaflet 'click' event. The first line in your click event should clear all existing selections.

In the case of a 'click' on a feature this will clear any existing selections (if they exist) and select the current feature.

In the case of a 'click' on a basemap (no features present) this will simply clear the existing selection.

For reference you can find Leaflet event documentation here.

  • 1
    Radar - thanks, I ended up dropping my cartoDB layer event and using map click only. on map click I take the latlng from the event and sent an ST_DWithin query to PostGIS through the carto api. I can set a tolerance for the mouse click this way.
    – geo_james
    Commented Jan 9, 2014 at 22:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.