Animiertes Scrollen mit jQuery

Aus Wolfgang Wagners Wiki


Bei klick auf einen internen Anker-Link wird nicht direkt zum Link gesprungen, sondern sanft dorthin gescrollt.

$(document).ready(function() {
	$('a[href*=#]').bind("click", function(event) {
		event.preventDefault();
		var ziel = $(this).attr("href");
 
		$('html,body').animate({
			scrollTop: $(ziel).offset().top
		}, 2000 , function (){location.hash = ziel;});
});
return false;
});

Mit Vanilla JS:

document.addEventListener("DOMContentLoaded", function() {
  const links = document.querySelectorAll('a[href*="#"]');
  
  links.forEach(function(link) {
    link.addEventListener("click", function(event) {
      event.preventDefault();
      const targetId = this.getAttribute("href").substring(1); // Entferne das '#' Zeichen
      
      const targetElement = document.getElementById(targetId);
      
      if (targetElement) {
        const targetOffsetTop = targetElement.getBoundingClientRect().top + window.scrollY;
        
        window.scrollTo({
          top: targetOffsetTop,
          behavior: "smooth"
        });
        
        // Füge den Hash zur URL hinzu
        history.pushState({}, "", "#" + targetId);
      }
    });
  });
});