What sets the button click event apart from other element click events in a contenteditable div?

I am attempting to add text at the precise location of the cursor within a contenteditable div by clicking on another element. This functionality works flawlessly when clicking on a button, however, it does not work with any other element. Specifically, when I click on a button, the text is inserted at the cursor position, whereas for any other element clicks, it always adds the text at the beginning of the div. The code below demonstrates this behavior with both a Button click and a DIV click (note that it does not work for any other tag). What could be causing this discrepancy between the two types of clicks? Is there a way to make a DIV click behave exactly like a button click? Please keep in mind that JQUERY is not being used (though a solution involving VUEJS would also be acceptable). Thank you.

Here is the jsfiddle link http://jsfiddle.net/jwvha/2727/

function insertTextAtCursor(text) {
  document.getElementById('pre').focus();
  var sel, range, html;
  sel = window.getSelection();
  range = sel.getRangeAt(0);
  range.deleteContents();
  var textNode = document.createTextNode(text);
  range.insertNode(textNode);
  range.setStartAfter(textNode);
  sel.removeAllRanges();
  sel.addRange(range);
}
body {
  background-color: #CCC;
}

div {
  border: 1px #000 solid;
  background-color: #FFF;
  width: 900px;
  margin-left: auto;
  margin-right: auto;
  text-align: center;
  margin-top: 20px;
  margin-bottom: 20px;
  vertical-align: center;
  padding: 30px;
}
<!DOCTYPE html>
<html>

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Editor</title>
</head>

<body>
  <div contenteditable id="pre">
    Update text Here . This is contenteditable div
  </div>
  <div>
    <input type="button" onClick="insertTextAtCursor('TEXT')" value="Click here to insert text above"> ( This button inserts text at the cursors current positions)
  </div>
  <div onClick="insertTextAtCursor('TEXT')">
    <b>Click here to insert in the above  contenteditable div </b> ( This won't insert at the current position , but always at the position 1)
  </div>
</body>

</html>

Answer №1

When buttons are clicked, they do not automatically gain focus like other elements do. This can create issues if your function relies on the element having focus. After a successful click event (which includes mouseup + mousedown), the focus is set on the containing div first as it bubbles up the DOM tree. One way to avoid this is by listening to mousedown events and calling event.preventDefault(), or by triggering your function before the click event fires, using onmousedown.

For more information, you can check out this detailed answer.

var prevented = document.getElementById("prevented");
prevented.addEventListener('mousedown', event => event.preventDefault());

function insertTextAtCursor(text) {
  document.getElementById('pre').focus();
  var sel, range, html;
  sel = window.getSelection();
  range = sel.getRangeAt(0);
  range.deleteContents();
  var textNode = document.createTextNode(text);
  range.insertNode(textNode);
  range.setStartAfter(textNode);
  sel.removeAllRanges();
  sel.addRange(range);
}
body {
  background-color: #CCC;
}

div {
  border: 1px #000 solid;
  background-color: #FFF;
  width: 500px;
  margin-left: auto;
  margin-right: auto;
  text-align: center;
  margin-top: 20px;
  margin-bottom: 20px;
  vertical-align: center;
  padding: 30px;
}
<!DOCTYPE html>
<html>

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Editor</title>
</head>

<body>
  <div contenteditable id="pre">
    Update text Here . This is contenteditable div
  </div>
  <div>
    <input type="button" onClick="insertTextAtCursor('TEXT')" value="Click here to insert text above"> ( This button inserts text at the cursors current positions)
  </div>
  <div onClick="insertTextAtCursor('TEXT')" id="prevented">
    <b>Click here to insert in the above  contenteditable div </b> ( This won't insert at the current position , but always at the position 1)
  </div>
</body>

</html>

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

Choose an option to adjust the transparency of the image

I'm struggling with a select option and need some assistance. I have a select dropdown list where I want the image opacity to change from 0.3 to 1 when selected or onchange event occurs. The catch is, I can't use the value of the option because i ...

What is the best way to include a custom JavaScript file in my Vuepress project so that the functions can be accessed globally?

I inherited a Vuepress project from a former colleague and I'm facing an issue with referencing my custom Javascript file in a root component for global availability. It's tedious to refer to it in every component and it's not functioning as ...

Transferring numerous hefty JSON documents at once from React Native to Node.js

I am facing a challenge while attempting to upload multiple large JSON files from React-native to Node.js. The files are successfully uploaded, except for when the file size is large, causing it not to upload in one attempt. My suspicion is that: Due t ...

Wcf Service does not define Angular JS methods

I am utilizing a WCF Service within an AngularJS application. The WCF Service is functional, and I am attempting to display a list of user records from a SQL database. However, upon running the application, I encountered the following errors: angular.js: ...

Understanding how to parse an array of arrays in JavaScript can be a

Looking for a function that can extract a value from an array containing multiple arrays? Simply use getValueFromArray(array, [2, 4]) to get the 4th element of the 2d array within the main array. Check out the code snippet below: function getValueFromArr ...

An italicized Arial font appears especially bold

When using Arial italic on a website, I followed these steps: font-family: Arial; font-style:italic; font-weight:100; In Photoshop, the Arial italic font appears as thin as the regular version. However, on the website, it looks bold instead. I'm uns ...

What is the best way to obtain an XML result through a cross-domain request?

I am currently working on making a request to a specific website using JSONP for cross-domain reasons in order to receive back an XML result that I can work with. This is how I have initiated the process: (function($) { var url = 'http://www.website. ...

a gentle breeze gathers a multitude of entities rather than items

When utilizing a restful server with node.js and sending a collection of entities wrapped in one entity object (Lookups), everything seems to be functioning properly. However, the issue arises when breeze views the entities in the collection as plain objec ...

What is the reason for browsers retaining old code in Symfony 4?

My Symfony 4 app sometimes fails to refresh changes made to the code in the browser, which can be quite frustrating. For example, When I modify a class from col-md-5 to col-md-3, and then refresh the page, it still shows as col-md-5. This behavior seems ...

Tips for identifying text within HTML code

Looking for help with this HTML code: <span class="navbar-text navbar-nav company-title">aLine</span> The text "aLine" is displayed on the navigation bar. Can you guide me on how to locate this text using xpath? ...

What is the best way to position my menu icon and header text in alignment?

I’m having trouble aligning the menu hamburger icon and title on my website. I’ve tried various methods like wrapping them in a div and using display:inline-block, but they still won’t align properly. Can anyone provide guidance on how to achieve thi ...

JavaScript Error: Cannot read property 'b' of undefined

Whenever I attempt to establish inheritance in TypeScript, the following JavaScript code is generated: var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constr ...

Records were successfully updated and a confirmation message was received, however the changes did not reflect in the database

I am working on creating an "edit_post" page for my website to allow users to edit their previously posted content. Although I receive a notification saying "Updated data successfully," the changes are not being reflected in the MySQL database. <?php ...

Does Node.js offer a solution or module for converting Google Map polylines into a PNG image without the need for rendering HTML?

I'm attempting to generate a PNG image of polylines on a Google Map using Node.js on the backend without utilizing any view engine. I attempted to use the "webshot" Node.js package, but it was unable to save the polylines on the Google Map. app.get( ...

Creating a PDF document using html2pdf: A step-by-step guide

Currently, I am immersed in a project using React. The main goal right now is to dynamically generate a PDF file (invoice) and then securely upload it to Google Drive. In the snippet of code provided below, you can see how I attempted to create the PDF f ...

Add extra space to the dimensions of the div by incorporating padding

Showing my issue with an accompanying image: I am looking for a solution to include padding in the width: 50%; calculation. Currently, the first div's width is actually 50% + 2em because the padding was not factored in initially. Is there a way to i ...

Understanding the request URL in Ajax when receiving a response

How can the URL of a jQuery request be retrieved from the response received? Perhaps something like this: function retrieveUrlFromResponse(response, url){ requestUrl = url; } ...

Server Components can only receive plain objects and select built-ins from Client Components. Any classes or null prototypes will not be compatible

I am encountering an error when wrapping the App.ts with queryclientprovider: "Only plain objects, and a few built-ins, can be passed to Client Components from Server Components. Classes or null prototypes are not supported." Below is the code snippet from ...

What could be causing the "Uncaught SyntaxError" that is resulting in ChunkLoadErrors and hydration errors in my next.js application?

Hey there! I've recently started working on a next.js project. However, whenever I run npm run dev in Chrome, I encounter an error in the console: layout.js:160 Uncaught SyntaxError: Invalid or unexpected token (at layout.js:160:29) In addition to t ...

Utilizing React's createRef() for Enzyme testing

I am currently using the new React.createRef() api in one of my components. I am trying to figure out how to test if document.activeElement is equal to the current ref component. Here is the component code: export class Automatic extends Component { c ...