Home >Web Front-end >JS Tutorial >How Can I Implement Smooth Scrolling for Anchor Links Using JavaScript and jQuery?
Creating Smooth Scrolling for Anchor Links
Smooth scrolling enhances user experience when using anchor links to navigate within a page. This article provides two approaches to achieve this effect: a native method compatible with modern browsers and a jQuery implementation for broader support.
Native Method for Modern Browsers:
document.querySelectorAll('a[href^="#"]').forEach(anchor => { anchor.addEventListener('click', (e) => { e.preventDefault(); document.querySelector(this.getAttribute('href')).scrollIntoView({ behavior: 'smooth' }); }); });
jQuery Method for Older Browsers:
$(document).on('click', 'a[href^="#"]', function (event) { event.preventDefault(); $('html, body').animate({ scrollTop: $($.attr(this, 'href')).offset().top }, 500); });
Note: For elements without an ID, this variation should be used:
$('a[href^="#"]').click(function () { $('html, body').animate({ scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top }, 500); return false; });
Performance Optimization:
To improve performance, cache the $('html, body') selector:
var $root = $('html, body'); $('a[href^="#"]').click(function () { $root.animate({ scrollTop: $( $.attr(this, 'href') ).offset().top }, 500); return false; });
Updating URL:
For cases where you want the URL to reflect the current section, use this variation:
var $root = $('html, body'); $('a[href^="#"]').click(function() { var href = $.attr(this, 'href'); $root.animate({ scrollTop: $(href).offset().top }, 500, function () { window.location.hash = href; }); return false; });
The above is the detailed content of How Can I Implement Smooth Scrolling for Anchor Links Using JavaScript and jQuery?. For more information, please follow other related articles on the PHP Chinese website!