Home > Blockchain >  Leaflet/JS: Sidebar Resets When Clicking Outside of Default Scroll
Leaflet/JS: Sidebar Resets When Clicking Outside of Default Scroll

Time:04-12

I'm making a Leaflet website for a school assignment. To make it more user friendly on mobiles, I've moved the overlays control menu to an interactive sidebar, opened with a <button> (now hidden), like this (sorry for some texts in Czech, but they shouldn't be relevant for my problem): layers when opening sidebar.

If i then scroll like this and click on the encircled symbol, the layer is correctly added, but the scroll level of the sidebar resets back to the first state.

I'd like for my sidebar scroll level to stay the same after clicking on any out-of-scroll symbols. I've tried saving the scroll level when clicking and changing it back afterwards, but the transitions were not smooth, even with minimal timeout.

Is there a way to disable this "auto scroll refresh"? It seems to me that it's somehow connected to Leaflet updating the displayed layer on the map, but I honestly don't know.

CodePudding user response:

I have had a similar problem with a project, and in the end, I simply reduced the number of buttons, and made their icons a few pixels smaller, so that they would fit on any iPhone, Samsung, Xiaomi, etc. I will give you an example of the project (early stages), and you can see the result. Disclaimer: I am affiliated with this site; it's my personal research website, but there is zero spam there! Danger-free zone guaranteed, LOL! Take a look at it, on laptop and phone, and see the difference, and the source code. Ancient Rome Leaflet Map, earliest beginnings during the time of King Romulus

CodePudding user response:

So it turns out that my original idea of saving the scroll position and updating it after clicking was the right way to go, I just needed to adjust CSS property scroll-behavior. Here is part of my code which shows the full solution for anyone who might chance upon the same problem:

Leaflet:
(one overlay layer, which is part of overlays dictionary, later used as an input to L.control.layers)

// previous overlay layers above
"<table><tr><th><img src='./img/graves.png' onclick='resetScroll()'/></th><td><p>hrobky</p></td></tr></table>":L.geoJSON(graves).setStyle({
     color: "#669999",
     weight: "1",
     fillColor: "#669999",
     fillOpacity: "0.5"
}),
// remaining overlay layers below

JS function called onClick on <img> elements i used to activate/deactivate layers:

function resetScroll() {
     let scroll_position = document.querySelector(".leaflet-control-layers-scrollbar").scrollTop;
     window.setTimeout(() => {
          document.querySelector(".leaflet-control-layers-scrollbar").scrollTop = scroll_position;
     }, 1);
}

CSS:

.leaflet-control-layers-scrollbar {
     scroll-behavior: smooth;
}

I know that this might not be the most efficient or elegant method of doing what I wanted, but it works nonetheless.

  • Related