10th
October
2017
Chrome Anchor Link Not Working Fix
One of my single page sites that had been live for months with no changes suddenly had the menu stop functioning in Chrome only. I can’t find an exact reason for the break, but I did find a cross-browser JavaScript solve that fixes the issue nicely. Just add the snippet to your site and the links should work automatically. Note that this fix requires jQuery but can be converted to VanillaJS.
/* Navigation Fix -----------------------------------------------------*/ $(function() { $('a[href*="#"]:not([href="#"])').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); if (target.length) { $('html, body').animate({ scrollTop: target.offset().top }, 1000); return false; } } }); });
Someone reached out to me today for help as the fix broke their WordPress site. If you’re using WordPress, this version uses the compatibility version of jQuery they provide out of the box. Be sure to place it in a javascript file and not your functions.php. Rui was kind enough to confirm the fix also works for Drupal 7.
/* WordPress Navigation Fix -----------------------------------------------------*/ jQuery(function ($) { $('a[href*="#"]:not([href="#"])').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); if (target.length) { $('html, body').animate({ scrollTop: target.offset().top }, 1000); return false; } } }); });