text-fragment-target-matchable.html (1498B)
1 <!doctype html> 2 <title>Text fragment navigation helper.</title> 3 4 <script src="/scroll-to-text-fragment/stash.js"></script> 5 <script> 6 function isInView(element) { 7 let rect = element.getBoundingClientRect(); 8 return rect.top >= 0 && rect.top <= window.innerHeight 9 && rect.left >= 0 && rect.left <= window.innerWidth; 10 } 11 function checkScroll() { 12 let position = 'unknown'; 13 if (window.scrollY == 0) 14 position = 'top'; 15 else if(isInView(document.getElementById("text"))) 16 position = 'text'; 17 else if(isInView(document.getElementById("text2"))) 18 position = 'text2'; 19 else if(isInView(document.getElementById("text3"))) 20 position = 'text3'; 21 22 const target = document.querySelector(":target"); 23 let results = { 24 scrollPosition: position, 25 href: window.location.href, 26 target: target ? target.id : 'undefined' 27 }; 28 let key = (new URL(document.location)).searchParams.get("key"); 29 stashResultsThenClose(key, results); 30 } 31 function doubleRafCheckScroll() { 32 requestAnimationFrame(() => { 33 requestAnimationFrame(() => { 34 checkScroll(); 35 }); 36 }); 37 } 38 </script> 39 40 <style> 41 .spacer { 42 height: 10000px; 43 } 44 </style> 45 46 <body onload="doubleRafCheckScroll()"> 47 <div class=spacer></div> 48 <div hidden=until-found> 49 <div id=text>hiddentext</div> 50 </div> 51 <div class=spacer></div> 52 <div id=text2and3ancestor> 53 <div hidden=until-found> 54 <div id=text2>start</div> 55 </div> 56 <div class=spacer></div> 57 <div hidden=until-found> 58 <div id=text3>end</div> 59 </div> 60 </div> 61 </body>