Home >Web Front-end >JS Tutorial >How Can I Implement Smooth Scrolling for Anchor Links Using jQuery and Native JavaScript?
When utilizing anchor links to direct users to specific sections of a webpage, a smooth scrolling experience can enhance user accessibility and engagement. jQuery offers built-in features to achieve this effect.
To initiate smooth scrolling using jQuery, employ the following code:
$(document).on('click', 'a[href^="#"]', function (event) { event.preventDefault(); $('html, body').animate({ scrollTop: $($.attr(this, 'href')).offset().top }, 500); });
Modern browsers now support native smooth scrolling for anchor links. Implement this behavior with the following code:
document.querySelectorAll('a[href^="#"]').forEach(anchor => { anchor.addEventListener('click', function (e) { e.preventDefault(); document.querySelector(this.getAttribute('href')).scrollIntoView({ behavior: 'smooth' }); }); });
No ID Attribute: If the target element lacks an ID attribute but is identified by name, use this code:
$('a[href^="#"]').click(function () { $('html, body').animate({ scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top }, 500); return false; });
Performance Optimization: Cache the document root selector to improve performance:
var $root = $('html, body'); $('a[href^="#"]').click(function () { $root.animate({ scrollTop: $( $.attr(this, 'href') ).offset().top }, 500); return false; });
URL Update: To update the URL during scrolling, use this callback:
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 jQuery and Native JavaScript?. For more information, please follow other related articles on the PHP Chinese website!