Useful javascript snippets for the editor

I could submit a PR to New Format Pack that implements these two ideas of yours @MIZMU @gnomek.

Of course, I’d also implement a config so you can choose which buttons you want.

4 Likes

@ MIZMU
Check also this add-on:
Custom Styles (font color, background colour, classes)

@kleinerpirat
Thank you very much.

1 Like

As @kleinerpirat pointed out in another thread: useful snippet for adding custom keyboard shortcuts in the new editor (in Editor Scripts & Symbols form):
{
“File”: “”,
“Language”: “JS”,
“Post”: “”,
“Pre”: “(function(){const btn = document.querySelector(\”[title^=‘Increase indent’]\"); const state = btn.disabled; btn.disabled = false, btn.click(), btn.disabled = state;})();",
“Script”: “Indent”,
“Shortcut”: “Ctrl+shift+:”
}

Handy for those of us with keyboards that have symbols in the ‘wrong places’, for instance keyboards where colon is ‘shift dot’ making it impossible to press ‘ctrl+shift+.’

ok. this for font size:

 setFormat("fontSize", "7")

But it is only limited to a size between 1-7
I tried the following solution (source):

<script>
function changeFont() {
 
   setFormat("fontSize", "7");
 
   var fontElements = document.getElementsByTagName("font");
 
   for (var i = 0, len = fontElements.length; i < len; ++i) {
 
       if (fontElements[i].size == "7") {
 
           fontElements[i].removeAttribute("size");
 
           fontElements[i].style.fontSize = "30px";
			
       }
 
   }
  
}
</script>

But it unfortunately did not work.

Also, I tried to perform the same method on the font family and it also did not work.:

setFormat('fontName', "Arial");

I’m waiting for the experts …

It’s updated now (new upload): Remove Cloze Button and Hotkey - AnkiWeb

Without looking into it too much, I think the “current” approach would be to wrap the text in a <span>-tag and set the font size with CSS: font-size: 30px; font-family: Arial; . The <font>-tag is deprecated (<font> - HTML: HyperText Markup Language | MDN). You can get the calculated font-size (taking all CSS into account) with window.getComputedStyle(), i.e. something like window.getComputedStyle(document.activeElement.shadowRoot.firstElementChild).fontSize. So maybe do something like:

  1. Wrap selection in a span tag with a unique ID so that you know “it’s yours” (I usually use the UUID module for that)
  2. Get the computedStyle() for the span
  3. Populate your popup menu
  4. Apply the new font size directly to the span style

Now, having said that it is going to be a bit more tricky when you mix in that your selection might bridge other HTML tags, for instance start in one <li> and end in another - this will require splitting the <span> into two etc.

I ended up using:

f"setFormat('{style}', '{val}');"
style= fontName/fontSize