Switching up the default font style within TinyMCE

After successfully changing the default font within the editor using the guidelines provided here, I have encountered a new issue. The original default font no longer appears in the font drop-down list.

The previous default font was Verdana, and the new default is now MyCustomFont.

As I type in the editor, MyCustomFont displays by default. However, when attempting to switch back to Verdana (original default), nothing happens. It is possible to change to any other font family except Verdana. Additionally, selecting MyCustomFont from the drop-down list causes the content to be surrounded by a span with inline styles – a process that does not occur with the original default font.

It appears that there may be a missing piece of documentation explaining how to inform the editor (especially the font feature) that the font defined as default in the CSS should also be the default font within the editor itself.

Despite extensive research on Google, I have not been able to find a solution. Most resources seem to refer back to the mentioned documentation. Am I alone in facing this challenge? If not, I would appreciate any assistance! :)

Kindly note that the responses to this question do not address my specific concern.

Answer №1

it may be a bit late, but...

$('.texteditor').texteditor({
    configure : function(te) {
        te.onInit.add(function(te) {
            te.execute("fontName", true, "Arial");
            te.execute("fontSize", true, "2");
        });
    }
});

UPDATE

In case of TinyTextEditor version 4, as mentioned by @jason-tolliver and @georg, the correct syntax is:

te.on('init', function (te) {
    te.target.editorActions.executeCommand("fontName", true, "Arial");
});

Answer №2

// Setting up TinyMCE
$('#content').tinymce({
    setup : function(ed)
    {
        ed.on('init', function() 
        {
            this.getDoc().body.style.fontSize = '12px';
            this.getDoc().body.style.fontFamily = 'serif';
        });
    }
});

Answer №3

If you're having trouble applying Radius Kuntoro's solution directly to tinymce.init, here's another approach that might work for you.

This is how I initialize TinyMCE:

tinymce.init({
            selector: '#editor',
            menubar: false,
            plugins: ['bbcode'],
            toolbar: 'undo redo | bold italic underline',    
            setup : function(ed)
            {
                ed.on('init', function() 
                {
                    this.getDoc().body.style.fontSize = '12';
                    this.getDoc().body.style.fontFamily = 'Arial';
                });
            },
        });    

Answer №4

If you are using TinyMCE version 4.6.3, it appears that this is the recommended approach:

tinymce.init({
    setup: function (ed) {
        ed.on('init', function (e) {
            ed.execCommand("fontName", false, "Verdana");
        });
    }
});

Answer №5

According to information on the TinyMCE website, you can include a style sheet in your init function like this:

tinymce.init({
    content_css : 'path/to/style/sheet',
    body_class: 'define-class-name-without-dot-at-the-first'
});

This method works without needing any additional setup. Check it out on the TinyMCE webpage

Answer №6

For those of you utilizing the TinyMCE EditorManager, there are two events available: AddEditor and RemoveEditor. When a new instance of TinyMCE is created and the AddEditor event is triggered, the editor will not be fully initialized yet, resulting in a null value when calling getDoc().

To work around this, you can set up an init listener as shown below.

tinyMCE.EditorManager.on('AddEditor', function (event) {
    ... other code ...

    event.editor.on('init', function() {
      this.activeEditor.getDoc().body.style.fontSize = '12px';
      this.activeEditor.getDoc().body.style.fontFamily = 'Times New Roman';
    });

    ... other code ...
  }
});

This information applies to version 4.3.8 and beyond.

Answer №7

I faced challenges with the solutions provided for tinymce 4.x where I was unable to modify either the font size or font name. After numerous attempts, I finally discovered the solution. I want to acknowledge Jared's response, thank you! The following commands will not work with default settings:

tinymce.EditorManager.execCommand("fontName", false, "12px");
tinymce.EditorManager.execCommand("fontSize", false, "Arial");

The default font size is in "pt," not "px." You can either specify the displayed fontSize as "px" using [fontsize_formats][1] or simply use "pt" for the desired size. Additionally, tinymce does not seem to like when the whole font family is not included such as 'arial, helvetica, sans-serif'. These adjusted commands successfully worked on my site:

tinymce.EditorManager.execCommand("fontName", false, "12pt");
tinymce.EditorManager.execCommand("fontSize", false, "arial, helvetica, sans-serif");

Answer №8

After trying various solutions without success, I took matters into my own hands and fixed the issue using a custom logic approach.

editor.on('change', function (e) {
    let node = e.target.selection.getNode();
    if (node.nodeName === 'P' || node.parentNode.nodeName === 'BODY') {
        editor.dom.setStyle(node, 'font-size', "16px");
    }

    tinymce.triggerSave(); // ensuring textarea reflects the changes
});

Answer №9

I found a solution that worked for me:

  1. To change the font in your WordPress editor, locate the functions.php file in the root of your theme's directory at /wp-content/themes/yourtheme/. Add the following line after the opening PHP tag:

    add_editor_style('custom-editor-style.css');
    
  2. Create a new file called custom-editor-style.css in the same directory. Add the following CSS code to this file:

    @import url(https://fonts.googleapis.com/css?family=Open+Sans:400,700);
    * { font-family: 'Open Sans', sans-serif, Arial, Helvetica;}
    

After making these changes, clear your browser's cache to see the updated font in your WordPress editor.

For detailed instructions, you can visit this link:

Answer №10

I attempted to approach it this way. Using TinyMce 5, the editor generates a body tag within itself. Upon initializing the editor, I specified forced_root_block:'div', ensuring that every time something is entered, the root element will always be a div.

 let tinyMceBody = tinymce.activeEditor.getBody();
      let divs = $(tinyMceBody).children('div');
      for(let i =0; i<divs.length; i++) {
        divs[i].style.fontFamily = 'Nunito';
}

Therefore, I aimed to target all root elements and assign default styles to them.

When making edits, Tinymce wraps any edited content in a span block with a style attribute, overriding any manual styling applied within the editor. If no editing is done in the text editor, the default styling set on the parent element forced_root_block:'div' stands strong.

Consider devising your own solution based on the aforementioned technique to meet custom requirements. It appears that the library lacks robust built-in support for this issue. z

P.S:-

tinymce.activeEditor.dom.setStyles(tinymce.activeEditor.dom.select('div'), {'font-family' : 'Nunito'});

This applies to all divs, but my intention was to apply it only to the direct children of the body tag and not all divs (including nested ones). Nevertheless, this could also serve as a viable solution.

Answer №11

If you are using tinymce 5, you have the option to incorporate the fullpage plugin into the plugins array and then create a new key called fullpage_default_font_family. It is uncertain whether this functionality remains consistent with older versions of tinymce.

https://i.sstatic.net/uxzKa.jpg

Answer №12

Here is a solution that worked for me:

STEP # 1:

To customize the editor style, locate the functions.php file in the root of your theme directory at /wp-content/themes/yourtheme/. Open it up and add the following line after the PHP tag:

add_editor_style('custom-editor-style.css');

STEP # 2:

In the same directory, create a new file called custom-editor-style.css with the following content:

@import url(); * { font-family: 'Open Sans', sans-serif, Arial, Helvetica;} Now, don't forget to clear your browser's cache to see the changes take effect.

Sincerely, Tony Ngo

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

Utilizing React: passing a Component as a prop and enhancing it with additional properties

My question involves a versatile component setup like the one below const Img = ({ component }) => { const image_ref = useRef() return ( <> {component ref={image_ref} } </> ) } I am exploring ways to use this compo ...

Why isn't margin working with position: fixed?

I need help finding a solution for incorporating margin in a box within my App class. The issue is that the position fixed property doesn't seem to work as intended. <div className="App"> <div className="box"> ...

Can you explain how to invoke a class with express().use function?

Currently, I am delving into learning Node JS with TypeScript but have hit a roadblock with a particular issue. In my app.ts file, I have initialized the express and attempted to call the router class inside the app.use() method, only to encounter an error ...

Retrieve active route information from another component

We are utilizing a component (ka-cockpit-panel) that is not linked to any route and manually inserted into another component like so: .. ... <section class="ka-cockpit-panel cockpit-1 pull-left"> <ka-cockpit-panel></ka- ...

Setting up Redux Saga in a modular format

I am currently using create-react-app for my project. As I now need redux-saga to handle async operations, I am encountering an issue with setting up sagas in a modular manner. When I say modular, I mean having one main sagas file that exports all the comp ...

Center 3 elements horizontally using Flexbox, ensuring the center element is aligned properly

Is it possible to center 3 elements using flexbox on a page? The middle element should be centered on the page, while the left and right elements can vary in width. Please refer to the image below: https://i.sstatic.net/IVdz8.png I am not certain if this ...

Month and year selection feature in ExtJS 4 catalog

I recently came across an interesting Fiddle that featured a Month and Year picker for apps. After finding this Fiddle here, I noticed that it was built using Extjs 5.0, and it worked perfectly. However, when attempting to switch it to version 4.2.1, the l ...

Steps for creating scrollable boxes with uniform size using tailwindcss:1. Define a specific width and height for

<div className="overflow-x-auto p-5 gap-5"> <div className={` bg-orange-700 w-[300px] h-[300px]`}></div> <div className={` bg-orange-700 w-[300px] h-[300px]`}></div> <div className={` bg-orange-700 ...

A Promise is automatically returned by async functions

async saveUserToDatabase(userData: IUser): Promise<User | null> { const { username, role, password, email } = userData; const newUser = new User(); newUser.username = username; newUser.role = role; newUser.pass ...

How about starting a Node.js application with specific configurations?

Is there a way to develop a Node.js app that can be initiated with additional parameters? Here are a few examples: node myApp.js -nolog This command would initialize the app with the custom parameter noLog=true, preventing console logging. node myApp.js ...

Implementing restriction measures for deterring harmful conduct within ExpressJS

Recently, I was alerted to some potential vulnerabilities in the application I'm currently developing, particularly in relation to the JavaScript code on the front-end. These flaws could allow a user to exploit the system by clicking multiple buttons ...

The router component in "react-router-dom" is not functioning properly

My goal is to explicitly utilize history in my project. While I am familiar with BrowserRouter, I prefer to use Route and make history one of its properties. Upon running the program, I encounter this page: enter image description here Below is my AppRout ...

Utilize inline scripts within the views of Yii2 for enhanced functionality

I stumbled upon a jQuery code online that allows for the integration of Google Maps, and I'm looking to implement it in my application to ensure accurate address retrieval. You can find the jQuery code here. Currently, I am working with yii2 Advanced ...

JavaScript document string separation

Hi there, I'm a newbie here and could really use some assistance. I am struggling with creating a function and would appreciate any ideas... To give you an idea of what I need help with, I have a String and I want to check if it contains a specific w ...

Type-safe Immutable.js Records with TypeScript

I'm struggling to find a suitable solution for my query. I am aiming to define data types using an interface in TypeScript, but my data consists of Immutable.js records making it more complex. Please refer to the example provided below. interface tre ...

When using AutoComplete in MUI, I encountered an issue while attempting to assign a default value to the checkbox from an API. Instead of achieving the desired result, I received an error stating "(inter

Within this snippet, I am seeking to retrieve a default value from the API to populate a checkbox initially. I have employed the Material-UI Autocomplete component, which includes a defaultValue prop. Despite my efforts to utilize this prop, I am encounter ...

What are the steps to ensure the effective functioning of my checkbox filter?

Currently, my product list is dynamically created using jQuery. I now need to implement filtering based on attributes such as color, size, and price. I found some code that filters the list items by their classes, which worked perfectly for someone else. ...

Element misbehaving after a certain point

I'm encountering an issue with a piece of code that is not working as expected. The problem seems to be specifically with the after element. The desired behavior is for two lines to draw from the top left corner and the bottom right corner when hoveri ...

Chaining promises: The benefits of attaching an error handler during Promise creation versus appending it to a variable containing a promise

function generatePromise() { return new Promise((resolve, reject) => { setTimeout(reject, 2000, new Error('fail')); }); } const promise1 = generatePromise(); promise1.catch(() => { // Do nothing }); promise1 .then( ...

Troubleshooting: Issues with Jquery's has, find, contains functions

As I check whether an element contains another element, I've previously utilized the jquery element.has(secondElement) function. In my angularjs project, I make use of jquery within a directive where I transclude elements through markup using ng-tran ...