When making updates to the HTML code, the cursor unexpectedly moves to the beginning of the code tag

Whenever I try to type in the code box and the content updates with the script provided, my cursor keeps getting moved to the beginning of the code. What can I do to resolve this issue?

function MaintainCursorPosition(Control) {
  var target = $('.' + Control);
  target.keyup(function() {

    // Grab the current element.
    var e = $(this);
    // Get the text content.
    var textContent = e.text();
    // Replace any matches and wrap them with span tags.
    var newTextContent = text.replace(/(\![a-zA-Z]*)/g, '<span class="mark">$1</span>');
    // Update the html content of the original element.
    e.html(newTextContent);

  });

};

$(document).ready(function() {
  MaintainCursorPosition('form-control');
});
.hash {
  background-color: #808080;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<code class="form-control" id="test" contenteditable="true" style="height: 100%; min-height: 100px"></code>

Is there a way to fix this issue effectively?

Your time and assistance are greatly appreciated.

UPDATE

The key is not to have the cursor jump to the beginning of the text but rather return it to where I last entered text.

Answer №1

My suggestion for resolving this issue is to utilize separate elements - one for coding purposes set with a transparent color or other means of hiding its content, and another element specifically designated for displaying the desired output.

I trust this recommendation will prove beneficial.

Answer №2

To achieve functionality, consider utilizing the input event instead of relying on keyup. This way, the event will trigger after each input even while the key is being held down. Utilize the Selection and Range objects to adjust the caret position as needed. The Range object offers methods like setStart and setEnd for precise caret positioning.

For detailed information on these objects, refer to: https://developer.mozilla.org/en-US/docs/Web/API/Range and https://developer.mozilla.org/en-US/docs/Web/API/Selection (please note that some features may still be experimental).

Below is a basic example using your provided code snippet. It's important to note that this example may not be fully operational. You'll need to make adjustments to ensure the caret is correctly positioned when dealing with generated elements created by special characters. Additionally, you may need to address specific key inputs such as Suppr or Backspace in relation to extra elements.

function HastTagLocation(Controll) {
    var controller = $('.' + Controll);
    controller.on('input', function (evt) {
        // Saving the caret state
        var sel, range, start, end ;
        sel = window.getSelection();
        range = sel.getRangeAt(0);
        start = range.startOffset;
        end =  range.endOffset;

        // Retrieve the relevant code element.
        var e = $(this); 
        // Obtain the text content.
        
        var text = e.text();
        // Replace the matches and enclose them in a span tag.
        var text = text.replace(/(\![a-zA-Z]*)/g, '<span class="mark">$1</span>');
        // Set the HTML of the original element.
        e.html(text);

        // Restore the caret position
        range.setStart(this.childNodes[0], start);
        range.setEnd(this.childNodes[0], end);

    });

};

$(document).ready(function () {
        HastTagLocation('form-control');

    });
.hash {
    background-color:#808080;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<code class="form-control" id="test" contenteditable="true" style="height: 100%; min-height: 100px"></code>

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

Alert about the modification of web addresses

After updating my website, all of the URLs have changed, leading to traffic being directed to old URLs that no longer exist. However, most of these old URLs have corresponding pages on the new site. It seems that the majority of this traffic to the old UR ...

What is the reason that custom styling for a single react component instance does not function properly?

In my current view, I have integrated a react component as shown below: <Jumbotron> Lots of vital information </Jumbotron> I am looking to give this particular instance a unique style, like using a different background image. However, addin ...

Tips on choosing additional (sibling) elements with CSS?

My navbar has the following structure: <ul class="nav navbar-nav"> <li class="nav-item"><a href="#services">Services</a></li> <li class="nav-item"><a href="#work">Work</a></li> <li class ...

Effortless scrolling on specific div elements, rather than the entire body

Currently, I am utilizing the following code to achieve smooth scrolling for links: function filterPath(string) { return string .replace(/^\//,'') .replace(/(index|default).[a-zA-Z]{3,4}$/,'') .replace( ...

Preserving data in input fields even after a page is refreshed

I've been struggling to keep the user-entered values in the additional input fields intact even after the web page is refreshed. If anyone has any suggestions or solutions, I would greatly appreciate your assistance. Currently, I have managed to retai ...

JavaScript WYSIWYG Algorithm

Despite my searches on SO, it appears that most questions revolve around simply making a div editable using contenteditable="true". I am interested in finding the most effective method for tracking all formatting tags applied to a document. Merely togglin ...

Transform the numerical character into a checkbox within a table using AngularJS

In my HTML code, I am utilizing AngularJS to present data in a table. <div ng-controller="CheckCtrl"> <table class="table table-hover data-table sort display"> <thead> <tr> <th class="Serial_"> ...

"Effortlessly handle adding and removing items with a single button using

I am working on creating a button functionality where clicking it will either add or delete a record from the database. This button serves as a 'favorite' feature. The desired behavior is as follows; Upon clicking the 'fav' button, th ...

How can jQuery retrieve a string from a URL?

If I have a URL like http://www.mysite.com/index.php?=332, can jQuery be used to extract the string after ?=? I've searched on Google but only found information about Ajax and URL variables that hasn't been helpful. if (url.indexOf("?=") > 0) ...

React drag and drop feature now comes with autoscroll functionality, making

I am encountering an issue with my nested list Items that are draggable and droppable. When I reach the bottom of the page, I want it to automatically scroll down. Take a look at the screenshot below: https://i.sstatic.net/ADI2f.png As shown in the image ...

Applying the Active CSS class to a Bootstrap Carousel

I'm currently working with a bootstrap carousel that displays dynamic images fetched from a backend API. The challenge I'm facing is that I'm unable to set the active class for the individual slides. If I hardcode the active class, all slide ...

CSS failing to accurately calculate width when children have percentage values assigned

This CSS quirk is quite interesting... An inline-block container will correctly calculate width when using units like px, vw, em, etc. But it behaves differently when using a percentage-based measurement. Percentage Example: https://i.sstatic.net/saI0M.j ...

What is the process for creating a sub-menu for a dropdown menu item in Bootstrap 5?

https://i.sstatic.net/o4FLn.pngthis is my code which i have created this navigation bar with bootstrap and all of its drop downs but i want to add another drop down to the services drop down section inside of webdevelopment but it can't any easy solut ...

Troubleshooting CSS rendering issues on Chrome browser

Currently in the process of developing a new website based on an old template. The site appears as intended in IE, Safari, and Firefox, but for some reason Chrome is not rendering any of the css. Just to clarify, none of the links are functioning at this ...

What is the best way to simultaneously send JavaScript variable and form data in Django?

I am trying to send a JavaScript variable to a Django view using the ajax() method. Below is my code: $('#orderDetails').submit(function() { // catch the form's submit event $.ajax({ type: 'POST', ...

Animating images with Jquery

As a beginner in Javascript and Jquery, I am currently learning about image animation. However, I have encountered a question regarding moving an image from bottom left to top right within the window. Is there a more efficient way to achieve this compared ...

What steps should be taken to rectify open tags or quotes in the source code of CKeditor when a user forgets

When inserting data into MySQL using CKEditor and PHP, I encounter an issue when users input raw HTML containing open quotes or tags. How can I handle this problem? For instance, if a user enters content in the CKEditor source and leaves quotes open, how ...

Looking for a new slider option to replace the traditional Conveyor belt slideshow?

I have successfully used the Conveyor belt slideshow script from http://www.dynamicdrive.com/dynamicindex14/leftrightslide.htm. Now, I am looking to find another script that works similar to this one. Does anyone have any recommendations for a tool that ...

Design challenges, consisting of both fixed width and elastic elements, have been resolved

After searching through various posts, I couldn't find the solution I needed. Currently, I am working on a design in Photoshop and foresee a potential issue when translating it into html+css. Picture this: my center div is set at 960px with a semi-tr ...

Creating a loading spinner in a Bootstrap 5 modal while making an XMLHttpRequest

While working on a xmlhttprequest in JavaScript, I incorporated a bootstrap spinner within a modal to indicate loading. The modal toggles correctly, but I am struggling to hide it once the loading is complete. I prefer using vanilla JavaScript for this ta ...