Advertisement
jcunews

Count selection's characters and lines

Jan 4th, 2019 (edited)
479
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //GreaseMonkey: Count selection's characters and lines
  2. //2019-01-03, https://greasyfork.org/en/users/85671-jcunews
  3.  
  4. (function(displayTime, disp, timer) {
  5.   function dispClose(ev) {
  6.     if (ev) ev.preventDefault();
  7.     if (!disp) return;
  8.     clearTimeout(timer);
  9.     disp.remove();
  10.     disp = null;
  11.   }
  12.  
  13.   displayTime = 2000; //in milliseconds. 1000ms = 1 second
  14.  
  15.   addEventListener("keydown", function(ev, txt, msg) {
  16.  
  17.     //shortcut: CTRL+; without SHIFT or ALT
  18.     if (!(ev.ctrlKey && !ev.shiftKey && !ev.altKey && (ev.key.toLowerCase() === ";"))) {
  19.  
  20.       //when the message is displayed, keys except CTRL, SHIFT, or ALT, or the CTRL+L shortcut, will close the message
  21.       if (disp && !["control", "shift", "alt"].includes(ev.key.toLowerCase())) dispClose(ev);
  22.       return;
  23.     }
  24.  
  25.     ev.preventDefault();
  26.     if (disp) return;
  27.     txt = getSelection();
  28.     if ((txt.anchorNode === txt.focusNode) && (txt.anchorOffset === txt.focusOffset)) {
  29.       if (!(txt = document.activeElement) || !("value" in txt)) return;
  30.       txt = txt.value.substring(txt.selectionStart, txt.selectionEnd);
  31.     } else txt = txt.toString();
  32.     if (txt) {
  33.       msg = txt.length + " characters.";
  34.     } else {
  35.       msg = "No selection.";
  36.     }
  37.     if (disp) {
  38.       clearTimeout(timer);
  39.       disp.remove();
  40.     }
  41.     disp = document.createElement("DIV");
  42.     disp.innerHTML = '<div style="margin:13% auto;border:2px solid blue;width:15ex;text-align:center;padding:1ex 1.5ex;background-color:white;color:black;white-space:pre;font-size:16pt;line-height:normal">' + msg + '</div>';
  43.     disp.style.cssText = "position:fixed;z-index:999999;left:0;top:0;right:0;bottom:0;background-color:rgb(1,1,1,0.3);cursor:pointer";
  44.     disp.onclick = dispClose;
  45.     document.body.appendChild(disp);
  46.     disp.contentEditable = false;
  47.     setTimeout(dispClose, displayTime);
  48.   });
  49. })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement