MetaFilter highlight selected comment

On MetaFilter.com, adds a border to the selected comment to make it stand out visually, and adds "selected comment" to the small text to make it easy to search if you lose your place.

当前为 2019-09-04 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name MetaFilter highlight selected comment
  3. // @version 12
  4. // @grant none
  5. // @match *://*.metafilter.com/*
  6. // @run-at document-idle
  7. // @description On MetaFilter.com, adds a border to the selected comment to make it stand out visually, and adds "selected comment" to the small text to make it easy to search if you lose your place.
  8. // @locale en-us
  9. // @namespace https://greasyfork.org/users/324881
  10. // ==/UserScript==
  11.  
  12. // on load, run highlight and attach event listeners
  13. if (window.location.hash.substring(1) != "") highlightSelectedComment(window.location.hash.substring(1)); // Highlight selected comment on first load. No need to remove highlight on first load as it won't exist.
  14. window.addEventListener('hashchange', handleHashChangeEvent); // Run every time the hash changes.
  15.  
  16. function handleHashChangeEvent(event) {
  17. if (event.oldURL.split('#')[1] != null) removeSelectedCommentHighlight(event.oldURL.split('#')[1]);
  18. if (event.newURL.split('#')[1] != null) highlightSelectedComment(event.newURL.split('#')[1]);
  19. }
  20.  
  21. function highlightSelectedComment(newHash) {
  22. let divToHighlight = getTargetDiv(newHash);
  23. divToHighlight.style.outline = '.2em solid #9cc754';
  24. divToHighlight.style.outlineOffset = '.2em';
  25. divToHighlight.lastChild.innerHTML += '<span class=\'tehhundUserScriptSelectedComment\'>Selected comment. </span>';
  26. }
  27.  
  28. function removeSelectedCommentHighlight(oldHash) {
  29. let commentDiv = getTargetDiv(oldHash);
  30.  
  31. // Remove styles
  32. commentDiv.style.outline = '';
  33. commentDiv.style.outlineOffset = '';
  34.  
  35. // Remove 'Selected comment' text
  36. let allSelectedCommentsSpans = commentDiv.getElementsByClassName('tehhundUserScriptSelectedComment');
  37. for (selectedCommentSpan of allSelectedCommentsSpans) {
  38. selectedCommentSpan.remove();
  39. }
  40. }
  41.  
  42. function getTargetDiv(hash) {
  43. let anchor = document.getElementsByName(hash)[0];
  44. let targetDiv = anchor.nextSibling;
  45. return targetDiv;
  46. }