skip to Main Content

The docs are fairly clear on how to add a custom toolbar button but what I need to be able to do is to set/unset a CSS property of the currently selected text using the button.

Specifically I need to be able to set/unset the CSS property "writing-mode" to/from "vertical-rl" for the currently selected text when the button is selected.

How can I do this?

2

Answers


  1. Chosen as BEST ANSWER

    Thank you for your reply it lead me to what seems to be working for me. Which is this (I still have more testing to do):

    window.addEventListener('DOMContentLoaded', () => {
      tinymce.init({
        toolbar: 'vrt_btn',
    
        setup: (editor) => {
          editor.on('Init', e => {
            tinymce.activeEditor.formatter.register("vrt", {
              selector: "p, div, h1, h2, h3, h4, h5, h6",
              classes: "vrt",
              styles: { "writing-mode": "vertical-rl" }
            });
          });
    
          editor.ui.registry.addButton('vrt_btn', {
            icon: 'edit-block',
            tooltip: "Set text to vertical",
            onAction: () => tinymce.activeEditor.formatter.toggle("vrt")
          });
        }
      });
    });
    

  2. To achieve this functionality, you’ll need to write some JavaScript code that interacts with the selected text in the document and applies the desired CSS property.

        function toggleWritingMode() {
         // Check if any text is selected
         if (window.getSelection().toString().length !== 0) { 
         current value
            document.execCommand('styleWithCSS', false, true);
            document.execCommand('styleWithCSS', false, false);
            document.execCommand('insertHTML', false, '<span class="vertical- 
            text">' + window.getSelection().toString() + '</span>');
           }
         }
    
        // Function to initialize the toolbar button
        function initializeToolbarButton() {
        // Create a button element
        var button = document.createElement('button');
        button.innerHTML = 'Toggle Writing Mode';
    
        // Add an event listener to toggle writing mode when the button is clicked
        button.addEventListener('click', function() {
            toggleWritingMode();
        });
    
        // Add the button to your toolbar (assuming you have a div with id "toolbar" for your toolbar)
        document.getElementById('toolbar').appendChild(button);
    }
    
    // Call the initialization function when the document is ready
    document.addEventListener('DOMContentLoaded', function() {
        initializeToolbarButton();
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search