1

My Leaflet map has markers that open modals.

When a user clicks on the map, however, I would like for the modal to close. But the bit of code that makes that happen (below) interacts with the marker, and forces it to close as soon as it opens:

map.on('click', function(e) {
$('.modal').modal('hide'); });

I did get this to work—see the JSFiddle here: https://jsfiddle.net/askebos/Lh1y12uq/

But as you can see, the only reason it seems to be working is because it creates the following error:

Uncaught TypeError: e.preventDefault is not a function.

I imagine it's because the map.on('click'...) function is prevented from executing.

Any thoughts on how I can get to the same behaviour without the error?

Astrid
  • 11
  • 8

1 Answers1

0

The solution is to add an init() function that keeps track when a marker is clicked. Inspiration came from this question.

First, add the init() function to your code:

function init() {
    init.called = true;
}

Then call the function when the marker is clicked:

function markerOnClick(e) {
  init();
...
}

Make a function that fires when the map is clicked, but include an if/else statement that checks whether init.called has been set to true. If this is the case, reset init.called. If it has not been set to true, then the map was clicked elsewhere and any modals may close.

function mapClick () {
if(init.called) {
    init.called = false;
}
else{
  $('.modal').modal('hide');
}
}

Finally, bind the mapClick function to map clicks.

map.on('click', mapClick);

The function will no longer override marker clicks, and the error has been resolved as well. That still doesn't tell me why e.preventDefault caused an error, so any explanations would be welcome!

A working JSFiddle can be found here: https://jsfiddle.net/askebos/oesh59jr/

Astrid
  • 11
  • 8