7

I noticed that calling .click() on jQuery selected DOM elements in Leaflet ( such as anchor icons ) will not do anything -- the click event isn't propagated to the events created with L.DomEvents. For example, go over to bboxfinder and try to trigger the zoom out button's click event:

$('a[title="Zoom out"]').click();

Nothing will happen, the map won't zoom out. I jumped down the rabbit hole to figure out the why(s) and ended up with more questions than answers. My two favorite questions are listed below.

I'm hoping the answers for each question address two parts:

  1. Why is this behavior happening? Be as technical as you can so people can learn!

  2. What are the benefits of this behavior? This is a well-written, abstracted library. I assume they made these choices for reasons that are not easy for someone like me to see. Any guesses what those benefits are? For example, maybe these choices work well with mobile devices.

Questions

1. Why are the jQuery events not propagating to DOM elements? I can call click on the unwrapped jQuery DOM element ( see below ) and fire the event, but i assume jQuery would pass this event down for me:

// this works fine, notice we're grabbing the raw element
$('a[title="Zoom out"]')[0].click();

2. When i was digging around in the Leaflet source I noticed button events were created/bound with this code workflow below ( it also happens in 3rd party packages like L.Draw ). The question is why are we using all these events on a single button and how are they working together? And really, why is it like this? I've pulled the code below from this part of the source:

    L.DomEvent
     .on(link, 'click', stop)
     .on(link, 'mousedown', stop)
     .on(link, 'dblclick', stop)
     .on(link, 'click', L.DomEvent.preventDefault)
     .on(link, 'click', fn, context)
     .on(link, 'click', this._refocusOnMap, context);
1
  1. It seems that the 4 first lines of the snippet (click, mousedown, dblclick, prevetDefault) will prevent the default map behavior (zooming etc).
    I've experienced the need to prevent these defaults when I've created interactive control elements.
    The 5th line sets the function (in this case this._zoomOut/this._zoomIn) to the button's onClick attribute. The 6th line will refocus the mouse on the map so the user won't have to click on the map to keep interacting with it.
  2. I found this example which demonstrates how to create buttons on a leaflet.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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