hacker news - scroll to next most outer post

14/02/2025, 4:56:16 pm

  1. // ==UserScript==
  2. // @name hacker news - scroll to next most outer post
  3. // @namespace Violentmonkey Scripts
  4. // @match https://news.ycombinator.com/item*
  5. // @grant none
  6. // @version 1.0
  7. // @license MIT
  8. // @author -
  9. // @require https://cdn.jsdelivr.net/npm/@violentmonkey/shortcut@1
  10. // @description 14/02/2025, 4:56:16 pm
  11. // ==/UserScript==
  12.  
  13. const { register } = VM.shortcut;
  14.  
  15. const viewportHeight = window.innerHeight
  16. const outerMostCommentElements = Array.from(document.querySelectorAll(".comment-tree>tbody>tr:has(td[indent='0'])"))
  17.  
  18. VM.shortcut.register('n', () => {
  19. if(document.activeElement.type === 'textarea'){
  20. // Is this hackey? maybe.
  21. document.activeElement.value+="n"
  22. return
  23. }
  24.  
  25.  
  26. const scrollY = window.scrollY || window.pageYOffset;
  27. const buffer = 50; // Buffer for invisible padding
  28.  
  29. // Find the next element below viewport
  30. const nextElement = outerMostCommentElements.find(elem => {
  31. const elemTop = elem.getBoundingClientRect().top;
  32. return elemTop >= (viewportHeight - buffer);
  33. });
  34.  
  35. if (nextElement) {
  36. nextElement.scrollIntoView({ behavior: "smooth", block: "center" });
  37. }
  38.  
  39. // else {
  40. // // If no next element found, scroll to the last element
  41. // const lastElement = outerMostCommentElements[outerMostCommentElements.length - 1];
  42. // if (lastElement && lastElement.getBoundingClientRect().top < (viewportHeight - buffer)) {
  43. // lastElement.scrollIntoView({ behavior: "smooth", block: "center" });
  44. // }
  45. // }
  46.  
  47. // for (const elem of outerMostCommentElements){
  48. // const elemYPosition = elem.getBoundingClientRect().top
  49. // // -50 to give it a bit of a buffer as there is invisible padding and stuff.
  50. // const elemIsBelowBottomViewport = elemYPosition >= (document.body.scrollTop + (viewportHeight - 50))
  51.  
  52. // console.log(elemIsBelowBottomViewport)
  53. // console.log(elem.getAttribute("id"))
  54.  
  55. // if(elemIsBelowBottomViewport){
  56. // elem.scrollIntoView({behavior:"smooth", block:"center"})
  57. // break
  58. // }
  59. // }
  60.  
  61. });

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址