notepad: Tab-Unterstützung
authorMalte Bublitz <malte@rolltreppe3.de>
Sun, 2 Jun 2024 20:56:34 +0000 (22:56 +0200)
committerMalte Bublitz <malte@rolltreppe3.de>
Sun, 2 Jun 2024 20:56:34 +0000 (22:56 +0200)
js/main.js
js/notepad.js

index 5ad0a46e3a198bc759f32ac7c12e013a6e42061d..68d6285039f10e52ddb9ab9a2892bddff625a7d8 100644 (file)
@@ -10,9 +10,7 @@ window.onload = () => {
     whoami.update();
        //whoami.settings2();
     
-    document.querySelector(
-        "button#settings"
-    ).onclick = function() {
+    document.querySelector("button#settings").onclick = function() {
         //window.whoami.settings();
         //window.whoami.update();
                whoami.settings2();
index f0a213178da87f3bedb50d9732bff0ead4517a05..860ff01e704e9735fb940e837b8306f4925caf69 100644 (file)
@@ -9,19 +9,42 @@
  * @param {string} storageKey string local Storage key
  */
 window.notepad = function(selector, storageKey) {
-    //console.log("window.notepad(\""+selector+"\", \""+storageKey+"\")")
-
     let elem = document.querySelector(selector);
-
+       
+       /**
+        * Load content from localStorage if possible
+        */
        if (localStorage.getItem(storageKey) !== null) {
         console.debug("window.notepad(): Loading from LocalStorage")
                elem.innerHTML = localStorage.getItem("notepad");
                
     }
-
+       
+       /**
+        * Save to localStorage after loosing focus
+        */
     elem.addEventListener("focusout", function() {
         console.debug("window.notepad(): Focus lost. Storing on LocalStorage");
         localStorage.setItem(storageKey, document.querySelector(selector).innerHTML);
-               
     });
+       
+       /**
+        * Allow inserting Tabs
+        *
+        * @see https://jsfiddle.net/2wAzx/13/
+        */
+       elem.onkeydown = function(e) {
+        if (e.keyCode === 9) { // tab was pressed
+            // get caret position/selection
+            var val = this.value,
+                start = this.selectionStart,
+                end = this.selectionEnd;
+            // set textarea value to: text before caret + tab + text after caret
+            this.value = val.substring(0, start) + '\t' + val.substring(end);
+            // put caret at right position again
+            this.selectionStart = this.selectionEnd = start + 1;
+            // prevent the focus lose
+            return false;
+        }
+    };
 };