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?

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
Jandroide
  • 483
  • 2
  • 5
  • 8

4 Answers4

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();
    }
  });
Ilja Zverev
  • 2,366
  • 14
  • 13
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(); });
danwild
  • 715
  • 7
  • 16
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.

user3276552
  • 271
  • 3
  • 5
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();});
ofir_aghai
  • 181
  • 1
  • 3