Ways to correct inverted text in live syntax highlighting using javascript

My coding script has a highlighting feature for keywords, but unfortunately, it is causing some unwanted effects like reversing and mixing up the text. I am seeking assistance to fix this issue, whether it be by un-reversing the text, moving the cursor to the end of the contenteditable div, or simply correcting the problem altogether using only JavaScript and jQuery.

Visit my code snippet on jsfiddle

Below is the JavaScript code:

function UnColor() {
    var elem = document.getElementById("editor");
    var text = elem.textContent;
    elem.innerHTML = text;
}

function Color() {
    UnColor();
    var elem = document.getElementById("editor");
    var code = elem.innerHTML;
    code = code.replace("var","<span style='color:dodgerblue'>var</span>");
    code = code.replace(/"(.*?)"/g,"<span style='color:green'>&quot;$1&quot;</span>");
    code = code.replace(/&lt;(.*?)&gt;/g,"<span style='color:#F90'>&lt;$1&gt;</span>");
    elem.innerHTML = code;
}

setInterval(Color,1000)

Any help would be greatly appreciated! Thank you.

Answer №1

If you're experiencing the issue of the cursor moving while editing, there is a solution to fix it. Simply retrieve the cursor's position using the selectionStart property of your editor textbox and then set the selectionEnd property to that value after performing the replacement function.

For more detailed information on selectionStart and selectionEnd, refer to this answer.

Below is a sample code snippet taken from this answer to help you implement this fix:

document.getElementById('target').addEventListener('input', function (e) {
  var target = e.target,
      position = target.selectionStart; // Capture initial position
  
  target.value = target.value.replace(/\s/g, '');  // This triggers the cursor to move.
  
  target.selectionEnd = position;    // Set the cursor back to the initial position.
});
<p>The method <code>.replace()</code> will move the cursor's position, but you won't notice this.</p>
<input type="text" id="target" />

Answer №2

The error occurs because the textContent of the editor id is being assigned to its innerHTML. To fix this issue, simply change the variable name in the JavaScript code provided below:

function UnColor() {
    var elem = document.getElementById("editor");
    var text = elem.textContent;
    var elem2;
    elem2.innerHTML = text;
}

function Color() {
    UnColor();
    var elem = document.getElementById("editor");
    var code = elem.innerHTML;
    code = code.replace("var","<span style='color:dodgerblue'>var</span>");
    code = code.replace(/"(.*?)"/g,"<span style='color:green'>&quot;$1&quot;</span>");
    code = code.replace(/&lt;(.*?)&gt;/g,"<span style='color:#F90'>&lt;$1&gt;</span>");
    var elem2;
    elem2.innerHTML = code;
}

setInterval(Color,1000)

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

Displaying various elements with distinct properties in React using ES6

<---------------------MODIFICATION------------------------> I initially thought I needed multiple onChange functions, but after reviewing the answers provided, I discovered a solution thanks to the helpful user's response. With some experimentatio ...

Transform the Data into JSON format

I need assistance converting my data into the correct JSON format. The current structure of my data is as follows: [ "{ id:001, name:akhilesh, }", "{ id:002, name:Ram, }" ] My goal is to transform the above data into valid J ...

The implementation of an onclick event in a freshly created HTML element is functioning solely on the final element

One issue I encountered was that when I generated page number buttons at the bottom of a page, the onclick event only worked with the last button created. Below is an example of how the page buttons were displayed: https://i.stack.imgur.com/wHwI0.png ...

Guide to linking a specific event with JQuery event handlers

I have a Javascript function named Howto that is triggered by a button press: function howto(){ $('#elementtoupdate').ajaxSend(function() { //Code to run }); $('#elementtoupdate').ajaxComplete(function() { //Co ...

Why is my Laravel function retrieving outdated session data?

Currently, I am in the process of developing a shopping cart feature using session. My goal is to create a function that can update the quantity of an item in the shopping cart and refresh both the subtotal and the list of items in the cart displayed on th ...

Tips on customizing the MSAL login commands for successful integration with numerous users

Successfully implemented the code to login using a username and password combination with Cypress for a webapp integrated with MSAL. In the end-to-end Testfile: describe('Login with MSAL as xxUsername', () => { beforeEach(() => { cy.Lo ...

Guidance on implementing fallback font formats using FontFace API

I am exploring the FontFace API (not @fontface) and wondering if there is an easy way to include multiple font formats, similar to providing multiple sources in @fontface. Alternatively, is there a simple method to identify which font formats are supporte ...

Output JSON data from PHP for use in Javascript

Is there a way to effectively convert JSON data from PHP/Laravel into JSON for JavaScript? I have the JSON string from PHP, but it is only rendering as a string. How can I convert it to a JSON object in JavaScript? Take a look at my code below. $('#e ...

Tips for deleting all content within a designated html tag (including the tag itself)

Imagine you are dealing with a string like this: text = """<p>Bla bla bla.</p><p>Blo blo blo<a href="http://www.example.com">bli bli</a>.</p><p>blu blu<br> <span style="font-size: x-small;"><br> ...

What could be the reason behind the failure of this :after element?

I am facing an issue with the preloader on my webpage where the animation is not displaying as expected. The animation should appear on top of a dark black background before the page fully loads, but it seems to be missing. The CSS for the animation works ...

Transform a date string into a date entity

Collecting the user's input for the date and saving it as a string variable. The format of the value is Fri Aug 27 2021 00:00:00 GMT+0530 (India Standard Time) My goal is to convert this string back into a new Date() object in order to make additiona ...

"Utilizing flex-box to create a hover effect for child elements

I am attempting to create a grid caret with a top and bottom caret that displays a grey area when the user hovers over each side. <div class="control-wrap"> <div class="caret-wrap"> <span class="caret">▲</span> </div&g ...

Separate every variable with a comma, excluding the final one, using jQuery

I've developed a script that automatically inserts checked checkboxes and radio options into the value() of an input field. var burgerName = meat + " with " + bread + " and " + onion + tomato + cheese + salad; $('#burger-name').val(burger ...

The object of type 'NoneType' does not have the 'next_element' attribute

Here we have an HTML snippet of a website with a single itemprop="brand": <dd itemprop="brand" class="attributeValue-2574930263"> <a class="link-3970392289 link__default-1151936189 attributeLink-2414863004&qu ...

Express Promises Linked Together: Lack of Data in Last Stage

When handling put requests for my restful API, I utilize the findOneAndUpdate method of Mongoose. The password is left to the second step where the 'save' pre hook of Mongoose is used to hash the password. router.put("/:id", function(req, res, n ...

Checking Sudoku Solutions on Codewars

I have come across this JavaScript code which seems to be functioning correctly. However, I am curious about the line board[3][8] != board[8][3] and how it checks for repeating row and column numbers. Can someone please provide an explanation? Thank you! ...

Striking a balance between innovation and backward compatibility in the realm of Web Design/Development

Creating websites is my passion, and I enjoy optimizing them for various platforms, devices, and browsers. However, lately, I've been feeling frustrated. I'm tired of facing limitations in implementing my creative ideas due to outdated technolog ...

Does aoMap function exclusively with THREE.BufferGeometry?

Can you provide guidance on setting up an aoMap for a standard THREE.Geometry object? Is there a demo available to reference? var uvCoordinates = geometry.attributes.uv.array; geometry.addAttribute('uv2', new THREE.BufferAttribute(uvCoordina ...

Angular 2 TypeScript: Accelerating the Increment Number Speed

I'm working with a function in Angular 4 that is triggered when the arrow down key is pressed. Each time the arrow down key is hit, the counter increments by 1. In this function, I need to run another function if the counter reaches a certain speed. ...

Ways to disseminate arguments when dealing with an array of arrays in JavaScript

Struggling to pass an array as arguments into the join method on path in node, but hitting a roadblock: var path = require("path"); var paths = [__dirname]; var userInput = ["app", "js"]; paths.push(userInput); var target = path.join.apply(null, paths); ...