I used this Mapbox tutorial to build a map. When I load the map I created in CodePen, it works as expected. When you click a listing from the left menu, it zooms to the location. However, when I put the map on a website, clicking a listing from the left menu either reloads the page or scrolls the page up to the top. To see the behavior, scroll down on the website so that the map frame is centered, and then click a location from the list. For most items, it will scroll to the top of the page. I've experienced this behavior in Chrome, Firefox, and Safari on iOS.
I suspect it has something to do with the way it's building the list:
/* Add the link to the individual listing created above. */
const link = listing.appendChild(document.createElement('a'));
link.href = '#';
link.className = 'title';
link.id = `link-${location.properties.id}`;
link.innerHTML = `${location.properties.project_site}`;
But everything I've tried to change there just breaks it.
I also realized going back to the Mapbox tutorial that I was using that when I click a listing on their map at the end of the page, the page also scrolls down a bit. So I assume it must be something in the original code and not something that I've changed?
I tried to use the map code on a Wix website instead of a Squarespace website and had the same issue.
Because you made your <a>
elements link to #
, they will cause browsers to jump to the top on click. This does not happen, or rather is not visible, on Codepen because your map and sidebar take up the whole height of the page.
You can prevent the jump by slightly modifying this part of your code in your Codepen at lines 348 following, by adding an event
function argument and then calling event.preventDefault()
:
link.addEventListener('click', function (event) {
event.preventDefault()
// rest of the function
});
For semantics sake, it is also recommended or best practice to add the attribute role='button'
in your type of use of <a>
: link.role = 'button';
You can read more about it in these Stackoverflow questions: