TinyMCE version 5.x - Stand out with a specific selection in a personalized drop-down navigation bar

In my customized TinyMCE 5.x dropdown menu, there are 3 options that adjust the width of the editor. I am looking for a way to indicate the currently selected option, but I am unable to interact with the menu items once they are initialized. It seems like the menu items are not present in the DOM when the menu is closed.

I would prefer if my custom dropdown functioned like the font-size dropdown, which shows a check mark next to the selected size. Alternatively, I would be satisfied if it worked similar to the font-family dropdown, where the selected font is displayed as the menu toggle even when the menu is closed.

editor.ui.registry.addMenuButton('maxWidth', {
                        text: 'Width',
                        fetch: function( callback ){
                            var items = [
                                {
                                    type: 'menuitem',
                                    text: 'Full Width',
                                    onAction: function(){   changeSectionWidth("full");     }
                                },
                                {
                                    type: 'menuitem',
                                    text: '1600',
                                    onAction: function(){   changeSectionWidth(1600);   }
                                },
                                {
                                    type: 'menuitem',
                                    text: '1170',
                                    onAction: function(){   changeSectionWidth(1170);   }
                                },
                            ];
                            callback(items);
                        },
                    });

Answer №1

Having exhausted all avenues in search of a solution, I resorted to hacking something together, although I must admit I am not overly pleased with this approach. Nonetheless, it does the job:

    //LOCATE THE BUTTON GROUP (located in group 12, index starts at 0)
    let btnGroup = $(editor.editorContainer).find(".tox-toolbar__group")[11];
    if( btnGroup ){
        return false;
    }

    //GET THE SPECIFIC BUTTON IN THAT GROUP (located in slot 4, index starts at 0)
    let targetBTN = $(btnGroup).children()[3];

    //CLICK HANDLER FOR THE SPECIFIC MENUBUTTON
    $(targetBTN).on("click", function(){ 

        //USE A TIMER SO TinyMCE HAS TIME TO RENDER THE MENU
        window.setTimeout( function(){

            //APPLY YOUR OWN LOGIC HERE TO DETERMINE WHICH OPTION TO SELECT
            //this has to match the words in the button and is case-sensitive
            let selectedOption = "Option 2"; 

            //DESELECT OTHER OPTIONS
            //NOTE THAT I AM USING AN EXTRA CLASS "my-selected" WHICH I APPLIED TO THE UI SKIN.min.css BECAUSE HOVER DESELECTED THEIR HIGHLIGHTS AND I WANTED IT MORE PERMANENT
            $(".tox-selected-menu .tox-collection__item--active").removeClass("tox-collection__item--active tox-collection__item--enabled my-selected");

            $('.tox-collection__item[title="'+selectedOption+'"]').addClass("tox-collection__item--active tox-collection__item--enabled my-selected");

        }, 50); //WAIT 50 milliseconds so menu has time to be rendered

});

Answer №2

Update: Although this information may be outdated, it could still be beneficial to others.

One way to achieve this is by utilizing formats and leveraging the onSetup function for each menu item. Refer to the following working example:

editor.ui.registry.addMenuButton('maxWidth', {
  text: 'Width',
  fetch: callback => {
    // Define the options for width.
    var widthOptions = [
      {
        title: 'Full width',
        format: 'full_width',
      },
      {
        title: 'Width 2',
        format: 'width2',
      },
      {
        title: 'Width 3',
        format: 'width3',
      },
    ];

    var items = [];

    // Add each option to menu items.
    widthOptions.forEach(option => {
      // Register a custom format for each option.
      editor.formatter.register(option.format, {
        inline: 'span',
        classes: option.format,
      });

      items.push({
        type: 'togglemenuitem',
        text: option.title,
        onAction: action => {
          // Ensure only one option is selected. Deselect all but the clicked one.
          widthOptions.forEach(opt => {
            if (
              option.format !=
              opt.format
            ) {
              tinymce.activeEditor.formatter.remove(
                opt.format,
              );
            }
          });

          // Toggle the selected option.
          editor.execCommand(
            'FormatBlock',
            false,
            option.format,
          );
        },
        onSetup: function(api) {
          // Check if this option is selected when generating the item.
          if (
            editor.formatter.match(
              option.format,
            )
          ) {
            api.setActive(true);
          }

          return function() {};
        },
      });
    });

    callback(items);
  },
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

tips for obtaining the highest value among multiple keys within an array

How can I find the maximum value among multiple keys in an array? I previously attempted to find the maximum values for just three keys. getMaxValuefromkeys(values: any[], key1: string, key2: string, key3: string) { var val1 = Math.max.apply(Math, v ...

Using multiple Django FBVs to capture and save data with Ajax and jQuery

Within my Django application, I have implemented two function views - FV1 and FV2. FV1 is responsible for retrieving data from the database and populating form/formsets. In FV2, the goal is to utilize Ajax to transmit serialized data from the page (conta ...

"Utilize Selenium to navigate and select a menu option with a

In my dropdown menu, I am trying to use Selenium to move the mouse to the Documentation menu item and click on the App Configuration option within it. The mouse hover function is working properly, but I am unable to click on the App Configuration element. ...

Several buttons, each requiring to show distinct text

Currently, I am attempting to enhance an existing project that was graciously created for me. I must admit, I am quite new to this, so please be patient with me! In my project, there are 9 buttons, each triggering the display of a different image upon bei ...

Tips for assigning a standard or custom value using JavaScript

What is the best way to automatically assign a value of 0 to my input field when the user leaves it blank? Should I use an if statement { } else { } ...

The $route.reload() function seems to be ineffective in Internet Explorer

I'm currently using AngularJs to develop an application. The issue I am encountering is related to data not being refreshed in IE, even after executing the $route.reload() function. Strangely enough, this problem only occurs in Internet Explorer and w ...

Ways to stop the react-router from causing the page to refresh

Need assistance with React Router issue I'm working on a project in reactJs using react-router-dom v5. I have set up a default route for routing. <Redirect to={"someComponent"}/> The problem is that when I refresh the page, it auto ...

Using jQuery to extract contact information from Google: A step-by-step guide

I'm currently using Google's API to access my contact list information and after logging the output in the console function fetch(token) { $.ajax({ url: "https://www.google.com/m8/feeds/contacts/default/full?access_token=" + token. ...

Using JavaScript regex to eliminate content enclosed in parentheses, brackets, and Cyrillic characters

Is there a way to transform (Test 1 / Test 2) [Test 3] Отдел / Here is title - subtitle (by Author) - 1234 (5678-9999), descriptions (best), more descriptions into Here is title - subtitle (1234) (descriptions) using a combination of JavaScript an ...

AJAX: Displaying the contents of a folder. Issue with URL resolution

I'm attempting to showcase a collection of images stored in a specific folder within a div. My approach involves utilizing AJAX within a JavaScript file titled edit, which is positioned one directory away from the index route. This implementation is b ...

Issue with Highcharts: The useHTML flag is not functioning properly when trying to render labels

Currently, I am utilizing highcharts and a phantomjs server for rendering charts and labels. However, I have encountered an issue where the useHTML flag does not function as expected when rendering the labels. Following the instructions in the documentatio ...

The presence of an undefined variable in `esm.js` is resulting in an overwhelming amount of

After upgrading from Node v14 to Node v16, I encountered a strange error specifically when running node with node -r esm. The error message reads: ReferenceError: myVar is not defined This results in an extensive output of the esm.js module spanning 5000 ...

Using NextJS to navigate user journey by mapping an array of values from Formik to

I really appreciate all the help I've received so far, but I'm facing an issue trying to map an object with an array within it to the router. Here is my current code: const initialValues = { region: query.region || 'all', campt ...

The variable is unable to transfer successfully from JavaScript to PHP using ajax

I have a code that is designed to pass the values of all checked checkboxes to a PHP file in order to delete corresponding rows from a CSV file. The checkbox values are dynamic. <tr><td><span class="custom-checkbox"><input ty ...

Docz: Utilizing Typescript definitions for props rendering beyond just interfaces

We are currently using Docz to document our type definitions. While it works well for interfaces, we've run into an issue where rendering anything other than interfaces as props in Docz components doesn't seem to display properly. I'm seeki ...

chart.js version 3 does not display the correct date data on the time axis

Struggling to make chart.js work with a time axis is proving to be quite challenging for me. The code I have is as follows: <html> <head> <script src="https://cdn.jsdelivr.net/npm/moment"></script> <script src="https://cdnjs.clo ...

Animate owlCarousel slide motion in reverse when using the Prev and Next buttons

The default functionality of owlCarousel is to move to the right when clicking Next and to the left when clicking Prev. However, after applying animations, both directions always move in the same direction. Check out this sample on jsfiddle to see the iss ...

Overridden CSS rules

Having a slight CSS dilemma. Within my webpage's html, I have the following structure: <div class='box-div'> <div>Entry 1</div> <div class='hide'>Entry 2</div> </div> Here is my associated ...

Setting fixed width for table headers in Bootstrap 3

Can someone explain why the width of "th" is not fixed and new line breaks occur when the content is too big? Currently, the "th" width expands. How can this be fixed? The width of my first column is col-lg-2. Click here for an example image ...

It appears that using Jquery's .on function in combination with AJAX is not functioning as expected

What is the reason why this code snippet below doesn't work as intended? $(function() { $('#settings').on('click', '.link', function(e) { e.preventDefault(); alert('okay'); }); }); ...