Last Updated: 

CodeMirror Example: HTML, JS, and CSS Modes

CodeMirror is a versatile and highly customizable text editor implemented in JavaScript. It offers a wide range of modes for different programming languages, including HTML, JavaScript, and CSS. These modes provide syntax highlighting, code folding, and other features that enhance the coding experience. In this blog post, we will explore the fundamental concepts, usage methods, common practices, and best practices when using CodeMirror in HTML, JS, and CSS modes.

Table of Contents#

  1. Fundamental Concepts
  2. Usage Methods
  3. Common Practices
  4. Best Practices
  5. Conclusion
  6. References

Fundamental Concepts#

What is CodeMirror?#

CodeMirror is an open-source code editor written in JavaScript. It can be embedded into web pages to provide a rich text-editing experience for code. It supports multiple programming languages through different modes, which are essentially sets of rules for syntax highlighting, indentation, and other code-related features.

HTML, JS, and CSS Modes#

  • HTML Mode: This mode is designed to handle HTML code. It can recognize HTML tags, attributes, and entities. It provides syntax highlighting for different parts of an HTML document, such as opening and closing tags, tag names, and attribute values.
  • JavaScript Mode: The JavaScript mode is used for editing JavaScript code. It can identify variables, functions, keywords, and operators in JavaScript. It also supports features like code folding for functions and blocks.
  • CSS Mode: The CSS mode is tailored for CSS code. It can highlight selectors, properties, and values in a CSS stylesheet. It helps in quickly identifying different parts of a CSS rule.

Usage Methods#

Step 1: Include CodeMirror Files#

First, you need to include the necessary CodeMirror CSS and JavaScript files in your HTML document. You can either download them from the official CodeMirror repository or use a CDN.

<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF - 8">
    <meta name="viewport" content="width=device - width, initial - scale=1.0">
    <title>CodeMirror Example</title>
    <!-- Include CodeMirror CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.11/codemirror.min.css">
    <!-- Include CodeMirror JavaScript -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.11/codemirror.min.js"></script>
    <!-- Include HTML mode -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.11/mode/htmlmixed/htmlmixed.min.js"></script>
    <!-- Include JavaScript mode -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.11/mode/javascript/javascript.min.js"></script>
    <!-- Include CSS mode -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.11/mode/css/css.min.js"></script>
</head>
 
<body>
 
</body>
 
</html>

Step 2: Create a Textarea#

You need to create a <textarea> element in your HTML where the CodeMirror editor will be initialized.

<textarea id="code - editor"></textarea>

Step 3: Initialize CodeMirror#

In your JavaScript code, you can initialize CodeMirror on the <textarea> element with the desired mode.

<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF - 8">
    <meta name="viewport" content="width=device - width, initial - scale=1.0">
    <title>CodeMirror Example</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.11/codemirror.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.11/codemirror.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.11/mode/htmlmixed/htmlmixed.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.11/mode/javascript/javascript.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.11/mode/css/css.min.js"></script>
</head>
 
<body>
    <textarea id="code - editor"></textarea>
    <script>
        // Initialize CodeMirror in HTML mode
        var editor = CodeMirror.fromTextArea(document.getElementById('code - editor'), {
            mode: "htmlmixed",
            lineNumbers: true
        });
    </script>
</body>
 
</html>

Common Practices#

Changing Modes Dynamically#

You can change the mode of the CodeMirror editor dynamically. For example, you can have a button to switch between HTML, JS, and CSS modes.

<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF - 8">
    <meta name="viewport" content="width=device - width, initial - scale=1.0">
    <title>CodeMirror Example</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.11/codemirror.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.11/codemirror.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.11/mode/htmlmixed/htmlmixed.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.11/mode/javascript/javascript.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.11/mode/css/css.min.js"></script>
</head>
 
<body>
    <button id="html - mode">HTML</button>
    <button id="js - mode">JavaScript</button>
    <button id="css - mode">CSS</button>
    <textarea id="code - editor"></textarea>
    <script>
        var editor = CodeMirror.fromTextArea(document.getElementById('code - editor'), {
            mode: "htmlmixed",
            lineNumbers: true
        });
 
        document.getElementById('html - mode').addEventListener('click', function () {
            editor.setOption("mode", "htmlmixed");
        });
 
        document.getElementById('js - mode').addEventListener('click', function () {
            editor.setOption("mode", "javascript");
        });
 
        document.getElementById('css - mode').addEventListener('click', function () {
            editor.setOption("mode", "css");
        });
    </script>
</body>
 
</html>

Getting and Setting Content#

You can get the content of the CodeMirror editor using the getValue() method and set the content using the setValue() method.

// Get the content of the editor
var code = editor.getValue();
 
// Set the content of the editor
editor.setValue('<h1>Hello, World!</h1>');

Best Practices#

Error Handling#

When using CodeMirror, it's important to handle errors properly. For example, if a mode file fails to load, the editor may not work as expected. You can use error handling techniques in your JavaScript code to detect and handle such issues.

// Check if the mode is available before setting it
if (CodeMirror.modes['javascript']) {
    editor.setOption("mode", "javascript");
} else {
    console.error('JavaScript mode is not available.');
}

Performance Optimization#

If you are dealing with large code files, consider using features like lazy loading or limiting the number of lines that are initially rendered. CodeMirror provides options to configure these aspects to improve performance.

var editor = CodeMirror.fromTextArea(document.getElementById('code - editor'), {
    mode: "htmlmixed",
    lineNumbers: true,
    viewportMargin: Infinity // Lazy load lines outside the viewport
});

Conclusion#

CodeMirror is a powerful tool for creating code editors in web applications. The HTML, JS, and CSS modes provide syntax highlighting and other useful features for editing code in these languages. By understanding the fundamental concepts, usage methods, common practices, and best practices, you can effectively use CodeMirror to enhance the coding experience for your users.

References#