Last active
October 17, 2019 21:09
-
-
Save jpederson/e1ff286d1c80edf26ef1 to your computer and use it in GitHub Desktop.
Google maps smooth scroll to anchor outside map when clicking on anchor link inside the map marker info window. Not tested...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This line is different | |
// it attaches a google maps listener that fires when an info window is opened and populated. | |
google.maps.event.addListener(referenceToInfoWindow, 'domready', function(){ | |
// scroll handler | |
var scrollToAnchor = function( id ) { | |
// grab the element to scroll to based on the name | |
var elem = $("a[name='"+ id +"']"); | |
// if that didn't work, look for an element with our ID | |
if ( typeof( elem.offset() ) === "undefined" ) { | |
elem = $("#"+id); | |
} | |
// if the destination element exists | |
if ( typeof( elem.offset() ) !== "undefined" ) { | |
// do the scroll | |
$('html, body').animate({ | |
scrollTop: elem.offset().top | |
}, 1000 ); | |
} | |
}; | |
// THIS IS DIFFERENT :) | |
// We're targetting the "google maps-style info window" element, and finding all links inside it. | |
$('.gm-style-iw').find("a").click(function(){ | |
// Everything else is normal. | |
// only do this if it's an anchor link | |
if ( $(this).attr("href").match("#") ) { | |
// cancel default event propagation | |
event.preventDefault(); | |
// scroll to the location | |
var href = $(this).attr('href').replace('#', '') | |
scrollToAnchor( href ); | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment