`Cursor in ACE Editor jumping to start of the line`

Having a strange issue with my editor. Every time I type something, it automatically gets reversed because the cursor keeps jumping back to the beginning of the line.

For example, if I type 'Say this', it appears as:

:siht ekil puS

On pressing enter, it becomes:

gniht ot desaerc siht nI

:siht ekil puS

Below is the code for my client side:

const editor = ace.edit("editor");
editor.setTheme("ace/theme/cobalt");
editor.getSession().setMode("ace/mode/javascript");

// Rest of the code goes here...

Spent half an hour trying to resolve this issue :(

Answer №1

editor.setValue() resets the selection, including the caret position, by default. So, it is crucial to consider this when incorporating code:

var currentCode = editor.getValue();
var currentSelection = editor.selection.toJSON();
editor.setValue(currentCode + "\nNewLine");
editor.selection.fromJSON(currentSelection);

You may also need to handle saving and restoring session.getScrollLeft() / session.getScrollTop() values as well as folds using session.getAllFolds().

In collaborative programming scenarios, utilizing deltas with

editor.commands.on("afterExec", handler)
for synchronization rather than solely syncing the editor content is often recommended. I suggest exploring how others typically approach this for more insights.

Answer №2

Consider storing the cursor position in a global variable when setting initial json and updating it after editing is completed.

//Global variable to save cursor position.
var cursorPosition = editor.aceEditor.getCursorPosition();

const options = {
            'mode': 'code',
            onChangeText: function (jsonString) {
                //update cursor position
                cursorPosition = editor.aceEditor.getCursorPosition();
                let json = JSON.parse(jsonString.replaceAll("^\"|\"$", ""));
                editor.set(json);
                //set the editor with the new cursor position during initial edit.
                editor.aceEditor.moveCursorToPosition(cursorPosition);
            }
        }

const editor = new JSONEditor(container, options)

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

MongooseServerSelectionError: encountered ECONNRESET while attempting to read the server selection

Having some trouble connecting my Nodejs application to MongoDB Atlas. Encountered this error: After trying to connect, I got an error in the catch block: MongooseServerSelectionError: read ECONNRESET DB connection error: read ECONNRESET Here is the ...

Preventing Continuous Scrolling When a Popup Appears

I am struggling with keeping the scrolling disabled when a popup div is visible in the center of the screen. I have attempted to use an overlay in the browser, but it doesn't seem to be working. Any suggestions on how to achieve this using jQuery and ...

Prevent HTML from being escaped in data-binding while utilizing repeat-templates in Polymer

Hey there! <template repeat="{{item in items}}"> <div layout horizontal> <div>{{item['content']}}</div> <div>{{item['more_content'])}</div> ...

When the parent div overflows, the child div remains hidden within the boundaries of the parent div

<section class="margin-top-30"> <div class="row" style="position: relative;"> <div class="col-sm-4"> <div class="lightbgblock" style="overflow-x:visible;overflow-y:scroll;"> ...

Utilizing the `filterBy` function with a custom select list that changes dynamically

I'm currently in the process of constructing a form with an extensive selection of drop-down items utilizing vue.js. My approach involves implementing the dynamic select list as detailed in this documentation: However, I am interested in providing us ...

What is the best approach for handling asynchronous responses within a callback function?

I've implemented an API wrapper using the Createsend-Node package to interact with CampaignMonitor's API within a serverless function. The main goal is to provide feedback to the caller about the success or failure of adding a subscriber to Campa ...

Leveraging the jQuery live() function to optimize heavy usage of Ajax on a website

Trying to ensure that all scripts are properly executed as content is loaded and removed from the page using jQuery load has been a challenge. The most effective approach so far has been the live function, but I have encountered difficulties in getting it ...

Is it possible to have text links styled, but without any actual hyperlinking?

Today has been rough, and I'm struggling to find a solution to my problem. Here's the issue: I have some nice CSS for links, but I only want it to apply to text links, not images or divs. Just plain text. My current code looks like this: a { ...

Utilizing Robot Framework to select CSS attributes

The Selenium documentation provides an example of how to use Get Element Attribute: ${id}= Get Element Attribute css:h1 id However, I encountered a problem with this selector: ${VISIBILITY}= Get Element Attribute css:visibility mySidebar I ...

What exactly does the statement if(item.some((item) => !item.available) represent in typescript?

Can you explain the meaning of if(item.some((item) => !item.available))? While looking at some code randomly, I came across this snippet: if(item.some((item) => !item.available){ } I'm curious about what it signifies. Can you elaborate on it? ...

Attempting to retrieve the key of an object nested within a JSON structure

I'm trying to extract all the key names from a JSON object, but I seem to be missing some when using the Object.keys method: var myJSON = [ { "Employees_Name": "Bill Sanders", "Work_plan_during_my_absence": "Work from home", ...

I am facing issues with getting the delete function to properly function in my React

Issue with Delete Button Functionality in React While I am able to successfully delete an item using axios call in Postman, implementing the same functionality on the front-end in a React component seems to be causing problems for me. <button onSubmit ...

"Exploring the interactivity of touch events on JavaScript

Hi there, I'm currently facing an issue with the touch events on my canvas. While the mouse events are functioning correctly and drawing as expected, incorporating touch events seems to be causing a problem. When I touch the canvas, the output remains ...

Is Polymer more of a comprehensive framework compared to just a library? What is the best way to implement web components in a modular fashion

Web components aim to modularize the web, independent of any specific framework being used. The Polymer project offers the ability to create web components without being tied to a particular framework, meaning they should be compatible with any framework. ...

What is the best way to ensure that my theme button changer has an impact on all pages throughout my website, not only on the

Looking for some help here - I've got a button that changes the theme/colour of my website, but it only seems to work on the homepage and not on any other pages. Anyone know how I can fix this issue? Here's the JavaScript code: $(document).ready ...

Utilize MySQL/Javascript to determine percentages

I'm facing a challenge with an SQL query in Entrinsik's Informer. I need to calculate a percentage using JavaScript on the result, but unfortunately, Informer cannot access data down columns (such as the total for the percentage). Therefore, I ha ...

Using JQuery and JavaScript to store and dynamically apply functions

I have a code snippet that looks like this:. var nextSibling = $(this.parentNode).next(); I am interested in dynamically changing the next() function to prev(), based on a keypress event. (The context here is an input element within a table). Can someo ...

Background image not looping in SQL database filepath

I have an image uploaded to a specific folder, and the file path is stored in a table along with other information such as title and description. I want to display this information within a repeated div element on the webpage. While the other variables loo ...

What's the best way to get rid of the one-pixel gap between these elements on high-resolution displays like

http://jsfiddle.net/36ykrp9x/5/ HTML <div class="container"> <button>O</button><button>O</button> </div> CSS .container { width: 100%; background-color: rgb(120, 200, 200); text-align: center; } butt ...

Storing images in Firebase using React JS upon form submission

I've been attempting to upload an image to firebase storage using the following code: const firebase = useFirebase(); const handleSubmit = e => { e.preventDefault(); // state.title && dispatch(createItems(state)); ...