Start trial
PricingContact Us
Log InStart For Free

Mastering Javascript font color changes in TinyMCE

February 29th, 2024

5 min read

A letter having it's color changed with paint, and a JS icon, representing the dynamic changes of font color

Written by

Joe Robinson

Category

How-to Use TinyMCE

There’s always requirements where customers want to change the appearance of text in your app. So it’s frustrating when you’re locked out of modifying any added components, and are unable to make dynamic changes to elements like text size, font family, or change font color. What you need is a customizable component that handles text, text editing, and font color change.

TinyMCE is a rich text editor that offers the needed flexibility to change font color using JavaScript and TinyMCE’s APIs. They’re one example of how TinyMCE provides an effortlessly customizable experience.

What you’ll find in this guide is a step-by-step explanation of how to go about changing the font color in your app.

JavaScript can change font colors

Using JavaScript to change font colors gives you more flexibility as compared to using only HTML with CSS. A JavaScript solution allows for changing web app style sheets, which directly modifies CSS to change font color. You can change the internal HTML styles, update the content of a page style tags, or change the external HTML styles – thereby updating your app’s external CSS files.

✏️NOTE: The CSS attribute you need to change font color is the “color” attribute. You can use RGB, Hex, or a specific color name in your CSS style to change font color.

JavaScript can change font colors by updating the particular attributes of HTML text. For example, you can set up a class in an external style sheet that has the new font color. A JavaScript function then adds that class to the text you want to change, which then changes the appearance of text. For example:

function changeFontOkay() {
  const newFontColor = document.getElementsByTagName('body');
  newFontColor.setAttribute(class, 'greenOkayText');
}

(And the CSS):

body {
color: green;
}

Change font color for different situations

One of the most well known situations where JavaScript changes font color is when the mouse moves over text elements. It’s the mouseover and mouseout event. In this situation, the font color change alerts the customer that they can interact with the text. Maybe it’s a button, or a link you want them to follow.

Another situation is accessibility. It’s not just a matter of changing from light mode to dark mode, making the background darker, and the text lighter. High contrast modes can increase the text size, and change font color, and adjust the font color contrast with background. This makes text easier to read and understand for more customers, regardless of their visual abilities.

There’s more niche situations where JavaScript changes font color to provide a benefit to your customers. The following sections show how you can set up one more example – warning text color – in the TinyMCE rich text editor when customers are building content.

How to change font color with CSS in TinyMCE

There are a few prerequisites involved to test out TinyMCE’s abilities in this situation:

  • A text editor such as VS Code, Zed, or Sublime Text
  • Some knowledge of JavaScript, and CSS
  • Your TinyMCE API key, as TinyMCE requires a valid API key for using the Tiny Cloud CDN

Your API key: Your TinyMCE API key is FREE, and available now on your TinyMCE dashboard. You can log in using Google or GitHub credentials. Your API key also comes with a 14-day free trial of TinyMCE Premium plugins.

1. Get the demo essentials started

Set up a new index.html file in your development environment, and copy the following demo HTML to get started. This is based on the TinyMCE Content Management System (CMS) demo:

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>TinyMCE Landing Page Example</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700;900&display=swap" rel="stylesheet">
    
    <style>
        body {
            margin: 2rem;
        }
        main {
            max-width: 1100px;
            margin: auto;
        }
    </style>
</head>
<body >

    <textarea id="editor"><p>Type in some text, and then click away.</p></textarea>

</body>
</html>

And once completed, save the change.

2. Use TinyMCE APIs to change font color

In the demo HTML, include the following script tags into the document head section. This configures TinyMCE, including the Premium plugins that power a fully-featured CMS:

<script src="https://cdn.tiny.cloud/1/add-your-api-key/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script>

    <script>
        tinymce.init({
            selector: '#editor',
            plugins: 'a11ychecker advcode advtemplate advlist advtable anchor autocorrect autosave editimage image link linkchecker lists media mediaembed pageembed powerpaste searchreplace table tinymcespellchecker typography visualblocks wordcount',
            toolbar: 'undo redo | aidialog aishortcuts | styles fontsizeinput | bold italic | align bullist numlist | table link image media pageembed | spellcheckdialog a11ycheck code | inserttemplate',
            toolbar_sticky: true,
            toolbar_mode: 'wrap',
            height: 620,
            object_resizing: false,
            resize: false,
            image_caption: true,
            images_file_types: "jpeg,jpg,png,gif",
            style_formats: [
                { title: 'Heading 1', block: 'h1' },
                { title: 'Heading 2', block: 'h2' },
                { title: 'Heading 3', block: 'h3' },
                { title: 'Paragraph', block: 'p' },
                { title: 'Blockquote', block: 'blockquote' },
            ],
            advcode_inline: true,
            spellchecker_ignore_list: ['CMS', 'devs'],
            a11ychecker_level: 'aaa',
            advtemplate_templates: [
                {
                    title: "About us",
                    content:
                        '<h2>About our company</h2>\n<p><a href="<a href="https://tiny.cloud">https://tiny.cloud</a>">XYZ Inc.</a> is a global leader in providing innovative solutions to businesses. We provide our clients with the latest technology, state-of-the-art equipment, and experienced professionals to help them stay ahead of their competition. Our comprehensive suite of services, from cloud computing and big data analytics to mobile and e-commerce solutions, ensures that all of our clients have the resources they need to stay competitive in an ever-changing business landscape. Our commitment to customer service and satisfaction is second to none, and we strive to be a reliable and trusted partner for our clients.</p>',
                },
            ],
            content_css: 'https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css',
            content_style: `
            body {
              margin: 2rem;
            }
            .warningText {
              color: red;  
            }
            `,
         });
    </script>
    <style>
        body {
            margin: 2rem;
        }
        main {
            max-width: 1100px;
            margin: auto;
        }
    </style>

To add the JavaScript font color change configuration, include the following setup option function into the TinyMCE init script, just after the content_style option, and save the change.

            content_style: `
            body {
              margin: 2rem;
            }
            .warningText {
              color: red;  
            }
            `,

            setup: (editor) => {
                editor.on('focus', (e) => {
                  var getPara = tinymce.activeEditor.dom.select('p')
                  tinymce.activeEditor.dom.removeClass(getPara, 'warningText');
              });
                editor.on('blur', (event) => {
                  var getPara = tinymce.activeEditor.dom.select('p')
                  tinymce.activeEditor.dom.addClass(getPara, 'warningText');
              });
            }
         });
    </script>
    <style>
        body {
            margin: 2rem;
        }
        main {
            max-width: 1100px;
            margin: auto;
        }
    </style>

The setup option makes use of three TinyMCE APIs to get the paragraph elements in the editor, add a class to change font color, and remove the class to dynamically switch the font color back to the default.

The specific APIs involved: 

The blur and focus events are the main triggers for the font color change. When the customer works in the editor, the font stays as the default color. When they click away, it changes red. This could work in a use case when the TinyMCE text content is changed red until it is saved as part of warnings and alerts surrounding unsaved content.

✏️NOTE: This is only an introductory example of how TinyMCE APIs can change font color as needed. In production, the colors selected would need to be tested and checked for accessibility. For more on accessible content: 

3. Test the demo with content font color change

With the demo ready, you can make use of a localhost command, or other methods, to open the demo file in your browser, and test out the font color change:

TinyMCE dynamic color change working in a demo

More on style change with TinyMCE

There’s more you can achieve when it comes to setting up a font color change with TinyMCE. There’s other demos you can test out:

Contact us if you have any questions, or want to speak with us about what TinyMCE can provide for your web apps and projects.

JavascriptDesignUse Cases
byJoe Robinson

Technical and creative writer, editor, and a TinyMCE advocate. An enthusiast for teamwork, open source software projects, and baking. Can often be found puzzling over obscure history, cryptic words, and lucid writing.

Related Articles

  • How-to Use TinyMCEOct 10th, 2024

    How to Use AI Prompts for Content Creation in TinyMCE

Join 100,000+ developers who get regular tips & updates from the Tiny team.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Tiny logo

Stay Connected

SOC2 compliance badge

Products

TinyMCEDriveMoxieManager
© Copyright 2024 Tiny Technologies Inc.

TinyMCE® and Tiny® are registered trademarks of Tiny Technologies, Inc.