26

I'm working with the Leaflet JavaScript Library and attached a (working) map to my HTML Document. It is in the middle of the page, and when I'm scrolling down with my mouse wheel and arrive at the map, it automatically zooms into the map.

I want to scroll through the page without stopping at the map. Is there a way to activate the wheel zoom only after the first click on the map?

4 Answers 4

36

It's simple: create L.Map with scrollWheelZoom: false option, then add a listener:

map.once('focus', function() { map.scrollWheelZoom.enable(); });

If you need to toggle zooming:

map.on('click', function() {
  if (map.scrollWheelZoom.enabled()) {
    map.scrollWheelZoom.disable();
    }
    else {
    map.scrollWheelZoom.enable();
    }
  });
0
17

More of a comment/improvement on the toggle component of the accepted answer, which is great (thanks). But.

When interacting with a map, for many use cases the user also needs to click the map to perform their task, so this:

map.on('click', function() {
  if (map.scrollWheelZoom.enabled()) {
    map.scrollWheelZoom.disable();
    }
    else {
    map.scrollWheelZoom.enable();
    }
  });

May result in some unexpected behaviour once the user starts actually using the map.

I would suggest something that may seem a bit more intuitive the user - click off the map to disable mouse scrolling.

For example set your scrollWheelZoom: false as above, then:

map.on('focus', function() { map.scrollWheelZoom.enable(); });
map.on('blur', function() { map.scrollWheelZoom.disable(); });
0
7

Leaflet.Sleep will make your job easy, and it's plenty configurable

Basically, it turns off scroll events when they're not needed and "wakes" your map when they are.

I'd post code, but the defaults seem to get it right, so you likely won't need anything beyond <script src="path/to/leaflet-sleep.js"></script> and you'll have a map like this.

0
2

You can do that by only those 3 lines:

map.scrollWheelZoom.disable();
map.on('focus', () => { map.scrollWheelZoom.enable(); });
map.on('blur', () => { map.scrollWheelZoom.disable(); });

or:

map.scrollWheelZoom.disable();
this.map.on('click', () => { this.map.scrollWheelZoom.enable();});
this.map.on('mouseout', () => { this.map.scrollWheelZoom.disable();});

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.