Tutorial

Script zum Scrollen zum Anker einer Seite

Man hat eine Seite erstellt und nutzt Sprungmarken? Wäre es nicht vielleicht schöner, wenn die Seite weich zum Anker scrollt?
Mit dem hier angebotenen Script ist dies möglich, für HTML oder auch WordPress.

Hier eine Demo

Script für WordPress (jQuery)

Falls das Theme kein weiches Scrollen unterstützt, kann man folgendes einfügen:
Folgendes Plugin biete sich an:

jQuery für WordPress

(function ($) {
document.documentElement.style.scrollBehavior = 'auto'; // Elementor Fix
const speed = 600;
const menuItem = ".main-navigation a[href*='#']";
const nav = "#masthead"; // Navigations-Container
curUrl = window.location.href;
if (~curUrl.indexOf("#")) {
const startLink = curUrl.split("#"),
	  
idStart = startLink[1];

history.replaceState(null, null, ' ');
	if(idStart != "" && $("#" + idStart).length > 0) {	
marginTopStart = $(nav).outerHeight();
if($(window).width() < 768) {
marginTopStart = 0;
}	
$("body,html").scrollTop(0);
document.fonts.ready.then(function () {
setTimeout(function(){ 
$('html,body').animate({scrollTop: (($("#" + idStart).offset().top - marginTopStart))}, speed);
}, 100); 
});
}
	}
$(menuItem).click(function (event) {
const baseUrl = window.location.href,
link = $(this).attr("href");
const splitLink = link.split("#"),
id = splitLink[1];
if (baseUrl == splitLink[0] && ($("#" + id).length > 0 || id== "")) {
marginTop = $(nav).outerHeight();	
event.preventDefault();
if(id=="") {
$('html, body').animate({scrollTop:0}, speed);	
}
else {	
$('html, body').animate({scrollTop: (($("#" + id).offset().top - marginTop))}, speed);
}
}	
});
})(jQuery);
Kopiere Code

jQuery für HTML-Seiten

(function ($) {
const marginTop = 10, //Abstand nach oben
speed = 600, //Scrollgeschwindigkeit
menuItem = ".menu-item a[href*='#']", // verschachtelte Navigation
//menuItem = "header a[href*='#']",footer a[href*='#']",
//Multiple Selektoren
curUrl = window.location.href;
if (~curUrl.indexOf("#")) {
history.replaceState(null, null, ' ');
const startLink = curUrl.split("#"),
idStart = startLink[1];
$("body,html").scrollTop(0);
document.fonts.ready.then(function () {
$('html,body').animate({scrollTop: (($("#" + idStart).offset().top - marginTop))}, speed);
});
}
$(menuItem).click(function (event) {
const baseUrl = window.location.href,
link = $(this).attr("href");
const splitLink = link.split("#"),
id = splitLink[1];
if (splitLink[0] == baseUrl) {
event.preventDefault();
$('html, body').animate({scrollTop: (($("#" + id).offset().top - marginTop))}, speed);
}
});
})(jQuery);
Kopiere Code

Die ID im Menü versehen, absolute Pfade verwenden!
In WordPress individuelle Links auswählen und entsprechend anpassen.

https://meine-site/beitrag/#meineId