Mark the term on the backspace key and remove it after pressing the second backspace button

<html>

  <body>
    <div id="textareaId" contenteditable="true">
      Hello there
    </div>
    <button onclick=selectText(0,4)>Click to select</button>
    <button onclick=deleteSelectedText()>Click to delete <button>
    <script>
    // Assuming 'textareaId' is the ID of your contenteditable div
    const contenteditableDiv = document.getElementById('textareaId');

    // Function to select a range of text within a contenteditable div
    function selectText(start, end) {

      const range = document.createRange();
      range.setStart(contenteditableDiv.firstChild, start);
      range.setEnd(contenteditableDiv.firstChild, end);

      const selection = window.getSelection();
      selection.removeAllRanges();
      selection.addRange(range);
    }

    // Function to delete the currently selected text
    function deleteSelectedText() {
      const selection = window.getSelection();
      if (!selection.isCollapsed) {
        selection.deleteFromDocument();
      }
    }

    
    contenteditableDiv.addEventListener('keydown', (event) => {
      if (event.key === '<' || event.key === 'Delete') {
        selectText(0, 5);
      }
      if (event.key === 'Backspace' && !window.getSelection().isCollapsed()) {
        event.preventDefault(); // Prevent default backspace behavior
        selectText(window.getSelection().anchorOffset, window.getSelection().focusOffset); 
      } else if (event.key === 'Backspace' && window.getSelection().isCollapsed()) {
        deleteSelectedText(); // Delete highlighted text on second backspace
      }
      
     
    });

// Example usage: select and delete text from 10th to 20th character`your text`


  </script>
</body>

</html>

The selected word seems to be getting deleted on the first backspace. how do I change the function to highlight it first on backspace and then on second, delete it fully. I figured the highlighted area is just replace immediately on keydown so needs a different logic.

Answer №1

It seems like adding event.preventDefault(); before calling deleteSelectedText(); might be necessary in this case.

If you don't do this, the code will select the text first, but then the default behavior will take over and erase it.

Just to double-check, you could also include event.stopPropagation() and return false; after deleteSelectedText();

// To ensure proper functionality, add an event listener to the contenteditable div
contenteditableDiv.addEventListener('keydown', (event) => {
  if (event.key === 'Backspace' || event.key === 'Delete') {
    event.preventDefault();

    const selection = window.getSelection();
    if (selection.isCollapsed) {
      deleteSelectedText();
    } else {
      selectText(0, 5);
    }
    
    event.stopPropagation();
    return false;
  }
  
});

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

How do I automatically redirect a user after they login using react redux?

Currently, I am utilizing react redux in conjunction with Next.js. The goal is to redirect the user to a specific page if they meet certain requirements. I have implemented this logic within my useEffect function and it works as expected. However, upon r ...

Having trouble retrieving data in Next.js and passing it to client components. It's just not functioning as expected

After asynchronously fetching data, I am passing it to a client component as props. However, the state of the client component is not being properly set and displayed. The props are passing correctly, but the state seems to not update for some reason. Ser ...

What could be the reason for a code running successfully in node but not in the REPL environment?

This is the current script I'm working with: const lib = require('./lib.js'); const fs = require('fs'); const graph = fs.readFileSync('../js-working-dir/add_graph.pb', 'utf8'); const sess = new lib.Session(gr ...

The initial click event for the input element in Jquery is not functioning correctly

I found a jQuery date selector online and the script looked something like this... <script type="text/javascript> $(document).ready(function () { $("#date3").click(function() { $("#date3").scroller({ preset: 'datetime' }); wheels = []; whe ...

Tips for receiving a reply from a post request

After successfully making and completing a post request, I'm wondering about using console.log(res.valor) in the code to display the data: consultarCorreio(){ this.cartS.cart.valorTotalItems this.cartS.getCorreiosPrazoPreco(this.cartS.cart.pesoTot ...

Displaying a MySQL blob image in an HTML file with Vue.js: A step-by-step guide

Here is a Vue file that I have: export default { data(){ return{ info: { name: '', image: '', }, errors: [] } }, created: function(){ thi ...

Leveraging React hooks to combine an array and an object within an array

Struggling to incorporate an array and an object into another array. This is the setup in my constructor: const [dashboard, setDashboard] = useState({ loading: true, data: [], address: '' }) This is how I envision the final data structure: { ...

Switch Button JavaScript Library

My project involves creating a mobile website with a simple interaction where clicking on a div opens another div underneath it. The HTML structure consists of two stacked divs, with the CSS for the bottom div initially set to 'none'. Using JavaS ...

No adjustment in color upon switching themes

I've been struggling to achieve the desired outcome while working on a small coding task. The goal is to modify the color of the screen background, text, and button as illustrated in the uploaded image. I have three code files for this task - index, t ...

Retrieve JSON Object using a string identifier

I created a script that takes the ID of a link as the name of a JSON dataset. $('.link').click(function() { var dataset = $(this).attr("id"); for (var i = 0; i < chart.series.length; i++) { chart.series[i].setData(lata.dataset ...

Utilizing Node and Express to transform an array into a "Object" Map

For my latest project, I decided to build a web application using Node Express for the backend and Vue for the front end. While working on it, I encountered an issue where an array in an object was being converted to a map when sent to Express via jQuery. ...

Load only the essential parts of the jQuery library, excluding any unnecessary code

I am curious about the basics of loading jQuery. I am looking for a way to avoid loading the entire jQuery library every time, as it may not be necessary. Here are my questions: 1. Is it possible to load only essential parts of jQuery and then add more a ...

Avoid reloading the page when the form is submitted using form.trigger('submit') command

My current code functions properly when the user clicks on the form's submit button: // load dashboards when filter form is submitted $('div.active form.filter-form').submit(function (e) { // get subm ...

The toggle button is having issues functioning properly within a While loop

Is there a way to enable slideToggle for all my queries? Currently, it is only working on the first query. Any suggestions on how to resolve this issue? JS code $(document).ready(function(){ $("#SendCopy").click(function(){ $("#users").slideToggle("s ...

Retrieve the contents of a script using JavaScript

I have a script on my webpage that looks like this: <script> window.__INITIAL_STATE__ = {"meReducer":{"me":{"id":1234,"groupId":789,"},},//more code removed}; </script> I am looking to trigger a ...

Executing npm run build index.html results in a blank page being generated without any error messages or warnings

After building my react app with npm run build, I encountered a problem where clicking on index.html resulted in a blank page opening in the web browser. I explored several solutions to address this issue but none seemed to work. Some of the strategies I ...

Having trouble formatting JSON data in a jQuery datatable with accurate information

Currently, I am diving into the world of jQuery tables specifically for a report that I am working on. Despite successfully receiving the API response, I am facing challenges in binding it to the jQuery datatable. I have searched through various questions ...

Tips on how to horizontally align an icon and text using Material UI

As a newcomer to Material UI, I am facing an issue where my icon and text are not aligned: What I'm aiming for: This is the code I have so far: <div style={{ display: 'inline-flex', VerticalAlign: 'text-bottom', Bo ...

Retrieve the location of video(s) embedded in raw HTML code

When loading a webpage into my WebView, I am able to retrieve the raw HTML as text. This particular page contains various video elements that are embedded within it, and I am looking to extract their locations as a list of strings in order to download them ...

CSS Troubleshooting: Image failing to load

Having an issue with bootstrap/css. I'm trying to load an image from the source folder using this CSS code: background: url('../img/home.jpg') no-repeat; Unfortunately, the image is not showing up in my home section on the page. https://c ...