User:Mgunyho/common.js

// Don't put the target element right into the corner, add a small padding. // These seem like decent values based on manual testing. const offset_x = 16; const offset_y = -12;

// get the bounding rectangle of the 'anchor' to which the scroll position is usually set to function getAnchorRect { return document.querySelector("#content").getBoundingClientRect; }

function fixWindowPosition(target_x) { const target_y = getAnchorRect.y - offset_y; window.scrollBy({		left: (target_x == null || target_x === false) ? 0 : target_x - offset_x,		top: target_y - offset_y,		behavior: "smooth",	}); }

const first_heading_rect = getAnchorRect; const initial_target_x = window.location.hash ? // If the URL has an anchor, scroll to that. document.querySelector(window.location.hash).getBoundingClientRect.x	: // Only scroll sideways if we're to the left of the first heading. // This way we don't lose our position if we reload the page while in the middle. (first_heading_rect.x - offset_x > 0 ? first_heading_rect.x : false);

fixWindowPosition(initial_target_x);

// Fix behavior when clicking on subheading anchors in TOC window.addEventListener("hashchange", function(event) {	const new_hash = event.newURL.split("#")[1];	if (new_hash != null) {		event.preventDefault; // prevent browser from jumping to the location of the heading		fixWindowPosition( document.querySelector("#" + new_hash).getBoundingClientRect.x		);	} });

// jump to start of page if 'home' key is pressed document.addEventListener("keydown", function(e) {	if (e.key == "Home") {		e.preventDefault;		fixWindowPosition(getAnchorRect.x);	} })