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

What is the jQuery equivalent for converting this JavaScript code?

Here's a code snippet that I am struggling with: data=>{document.querySelector( "#os11.html-widget.gauge svg text[font-size='10px'] tspan" ).innerHTML = data.text I attempted the following solution: $("#os11.html ...

Sleek descending motion effect

I have created a simple function, but it is not animating smoothly and seems to lag... I am using it for a div sized at 1600x700 pixels on page load $(document).ready(function(){ $('#slider').slideDown(500); }); Is there any way to ensure s ...

Margin not being applied to last element in parent - any ideas why?

Why does the margin of the last element, whether it is a <p> or <h1>, not have any impact? It should be pushing the background of the parent container downwards. .container { background: grey; } h1 { margin-bottom: 3em } p { margin- ...

Creating scalable React applications

Can you provide insights on the scalability of React Apps? What recommended approaches are typically employed to effectively handle and generate scalable states in web applications using Reactjs? * ...

Using jQuery to combine a variable with the image source in order to replace the image attribute

I am trying to create a script that will display a greeting message to the user based on their local time. I found a script on Stack Overflow, but I am struggling with updating the image source. When I try to replace the image source, I encounter the follo ...

Exploring the width of Bootstrap 5 Tab Pane content

My issue lies with the content width of my tab panels - specifically, it doesn't work well with columns. I am unable to divide a tab-pane as col-md-7 and col-md-5 (refer to the screenshot below). I am unsure of how to resolve this issue. <div clas ...

Adjust the height setting of the React-Highcharts viewport

My initial configuration for highcharts looks like this:- function getInitialHighChartsConfig(chartType) { return { credits: false, chart: { type: chartType, height: 325, }, title: { text: '', useHTML: tr ...

Use Meteor to retrieve the value from the initial collection in order to locate the value in the second collection

Currently, I have two sets of data: Users, containing userId, firstname, and surname. Answers, containing answerId, questionId, and user. In the 'Answers' collection, the 'user' field corresponds to the userId of the user who provide ...

Restore the initial content of the div element

Currently, I am utilizing the .hide() and .show() functions to toggle the visibility of my page contents. Additionally, I am using the .HTML() function to change the elements inside a specific div. $('#wrap').html(' <span id="t-image"> ...

Retrieve the file from Amazon S3 and download it

I'm having an issue with downloading a file from a directory outside of the root. Whenever I try, it defaults to looking in the root directory. I need users to be able to download these files on my site. The file was initially uploaded to Amazon S3 a ...

Concealing other items in an array on selecting one item in React Native- A step-by-step guide

Currently, I have set up my view to display an array of items (Circle components) as shown in the image below: However, I am facing a challenge in hiding all other Circle components when I click on one of them. The onPress event is configured to zoom in a ...

The issue with the callback function not being triggered within a self-repeating loop

As I work on creating a user-script to incorporate a trailer video into a website, I encountered an issue with the callback function in my script. The goal is to filter the real source of the video from different URL formats, but for some reason, the callb ...

Proper Sequence of Bootstrap Header Configuration

I'm working on creating a header/navbar using bootstrap, but I'm unsure about the correct order and method to achieve this. This is how I want it to look: And when collapsed: Should everything be contained within the NAV tag? I have a header ...

Is there a way in JQuery to apply the CSS of one element to another selected element?

I'm curious if there is a JQuery function available that can be used to transfer the exact CSS styles from one element to another. I want all the CSS properties to be applied without any additional inheritance. For example: <div id="d1"> &l ...

Submitting incomplete values from a Jquery form to a MySQL database

I'm having an issue with my IntelXDK HTML5 mobile app where the form is submitting empty values to the MySQL database. Here is the HTML code for my single file app: <label class="item item-input widget uib_w_6 d-margins" data-uib="ionic/input" da ...

Collapsed Bootstrap navigation bar on mobile devices

Hello everyone, I am currently using the latest version of Bootstrap for my website. However, I have encountered an issue where the navigation collapses on mobile view. Could anyone provide assistance? Website: Below is a snippet of my HTML code: <he ...

Leveraging global variables within Vuex state management strategy

I have successfully added custom global variables into Vue by injecting them. Here is the code snippet: export default function (props, inject) { inject('models', { register(name) { const model = require(`@/models/${name}. ...

Ways to implement div on hover in my table's td cells

Here is the HTML table code I have: <table border='1px'> <tr> <td id='td'>first</td> <td>last</td> <tr> <td id='td'>newFirst</td> <td>newSecond</td> </t ...

An improved method for fetching data from the server at regular intervals of x minutes

Is setInterval the best way to periodically check for updates in a database and update the UI accordingly, or are there better approaches that I should consider? I've read conflicting opinions on using setInterval for this purpose, with some sources ...

Upon hitting submit, the form remains unresponsive

I have been developing a permissions system for my NodeJS project (Using the SailsJS MVC) and encountered an issue. After resolving my initial error as detailed here, I am now facing a problem where the form is unresponsive. It neither shows an error in th ...