Add HTML syntax highlighting to a text area for coding purposes

I am facing a seemingly straightforward issue, but I worry that it may be too complex for me to handle on my own. My goal is to incorporate a textarea into a webpage where users can input HTML code, click a button, and have the interpreted HTML displayed in a div next to the code, similar to the "try it" sections on w3schools.

Currently, I have most of the functionality in place and it works almost as expected - the code renders correctly when the button is pressed. The next challenge is to add syntax highlighting to the textarea so that the text changes color based on the tag or attribute typed, mimicking the behavior of notepad++ with blue text for tags and red for attributes, for example.

I believe the solution involves parsing the content of the textarea word by word, comparing against all possible tags and attributes, and then updating the textarea with colored text. It seems like this may not be achievable with a standard textarea, potentially requiring a specialized applet instead. Can anyone suggest the most efficient approach to achieving this? While I am close to finishing my computer science degree, my web programming knowledge is limited, although I have begun exploring jquery and jsp, along with some experience in HTML/CSS/Javascript.

Answer №1

I once had a similar need and came across an amazing Javascript-based code editor that can be integrated into your web application.

Take a look at the live demo here: Code Mirror HTML editor demo

You can also download Code Mirror from their website: Code Mirror home/download

For detailed instructions, refer to the User Manual: Code Mirror user-manual

This editor offers features like syntax-highlighting, automatic indentation, intelligent auto-complete suggestions, and more.

Implementing it is as easy as including the following script:

<script src="codemirror.js"></script>
<link rel="stylesheet" href="codemirror.css">

To replace a text-area with the Code Mirror editor, you can use the following code snippet:

var myCodeMirror = CodeMirror(function(elt) {
  myTextArea.parentNode.replaceChild(elt, myTextArea);
}, {value: myTextArea.value});

If you prefer using JQuery, this is how you can do it:

var myCodeMirror = CodeMirror(function(elt) {
    $('#my-code-input').replaceWith(elt);
}, {value: $('#my-code-input').val()});

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

How can I make an HTML button function with a JavaScript script?

When I click a button in an HTML file, it should trigger a function in a JavaScript file to display an alert that says "hey." However, this simple task is not working for me and I am unsure why. Java Script is enabled in my browser (Google Chrome) and I am ...

Angular's ng-for directive allows for easy iteration over a collection of

I have a list of links that I am looping through using the ng-for directive. Each link is supposed to display an icon with different timing intervals thanks to a plugin called wowjs. The first link should appear quickly, while the last one should appear sl ...

Error encountered: Unable to assign onClick property to null object

Hey everyone, I'm running into an issue with my JavaScript. It keeps throwing a TypeError: Cannot set properties of null (setting 'onclick') at SignUp.js:4:43 <HTML> <body> <div class="input-box"> <span class="deta ...

:root variables not being recognized in SCSS and Vue3 with Vite

I am encountering an issue with setting variables in my root SCSS file, as they are not being recognized correctly. Within my Vite configuration, I have included the following to import my styling: css: { preprocessorOptions: { scss: { additio ...

Trouble with displaying events on Angular UI-Calendar

I've been working with Angular UI Calendar and following the steps outlined on their website: http://angular-ui.github.io/ui-calendar/ Despite implementing everything correctly, I'm facing an issue where the events fetched from my API are not s ...

My current objective is to extract the information from a specific item within a combobox by implementing the following code

alert($("select[name="+this.name+"] option:selected").text()); However, I am not receiving any output unless I explicitly specify the name of the combobox instead of using this.name. This issue may be related to the way quotes are being handled. ...

Leverage the power of AJAX for searching in Laravel 5.3

This section contains views code related to form submission: {!! Form::open(['method'=>'GET','url'=>'blog','class'=>'navbar-form navbar-left','role'=>'search']) !! ...

The SSE emitter sends out multiple signals, but occasionally the browser fails to receive them

When setting up an event emitter in a node.js/express application, I noticed that the events emitted are sometimes received multiple times by the front-end listener. Although I can confirm that emit is only called once, the same event gets emitted up to 4 ...

Guide to effectively utilizing jQuery Deferred within a loop

I have been working on a function that needs to loop through a dataset, updating values as it goes along using data from an asynchronous function. It is crucial for me to know when this function finishes running the loop and completes all updates. Here is ...

I am looking to generate div elements using JavaScript to avoid the tedious task of individually creating numerous divs

Instead of manually typing out multiple div tags in the HTML, I would like to dynamically generate them using JavaScript and display them on the page. Below is an attempt at achieving this, but it appears to not be functioning correctly. var arr = {}; f ...

Mastering the usage of AngularJS Directive controllerAs syntax with scope is key to developing

I have included my code below: // HTML <body> <h1>{{foo.name}}</h1> <my-directive></my-directive> </body> // Scripts app.directive('myDirective', function() { return { restrict: 'E', ...

Pure CSS tab system that prevents label propagation using anchors

I am in the process of creating a tab system using only CSS with the help of the :target and :checked pseudo classes. However, I have encountered an issue where an anchor inside the label is not triggering the :checked. When clicking on the anchor, the :c ...

How about trying out some dropdowns?

Following the issue I mentioned in my previous question titled Margin-Right on CSS not working, I am currently engaged in a creative endeavor to redesign my school's website homepage. The progress so far has been significant, but I now require some as ...

"Exploring the best way to retrieve the angular filter value within a Node.js environment

Currently, I am facing an issue with accessing the value in Node.js using req.body when it is stored in ng-model. The ng-model includes an AngularJS filter, and I need to retrieve this filtered value from the input field in Node.js through req.body. Below ...

Why is the script from URL "http://.../js/myscript.js" not executing as expected after being fetched?

Is it possible to have the server run a JavaScript file specified in a URL, such as "http://.../js/script_name.js", and return the result instead of just displaying the source code? I am assuming that the server is using node.js. ...

Utilize the ajaxStart and ajaxStop jQuery methods selectively for specific requests

Utilizing the AjaxStart and AjaxStop jQuery methods allows me to display and hide a loading message when an Ajax request is sent. Here is an example code snippet: $('<div><img src="images/searching.gif" align="absmiddle" bord ...

Ensure that the horizontal navigation items are equally spaced apart

I've managed to align my longer navigation bar items horizontally instead of vertically, but I'm struggling to evenly space them alongside the shorter items within the container. Despite trying various solutions found through research, I have not ...

Node.js square brackets notation for functions [function] or [function: isBuffer]

Apologies for what may seem like a beginner question. I've been exploring the global variable in node.js and I'm puzzled by the syntax. It appears to be a JSON object, but it's formatted as follows: reallyExit: [Function: reallyExit], bindi ...

"Resolving the problem of populating an empty array with JSON

My JSON structure at the top level is set up like this: { "video": [], "messages": [], "notifications": [] } In the database output stored in a variable called "result," I have data that I want to add to the "vide ...

Hiding the title property while displaying a JQuery tooltip

I have implemented a simple JQuery solution for creating hovering tooltips using text from elements' title attribute. While it is functioning adequately, I am looking to prevent the default browser behavior associated with the title attribute from occ ...