Learn how to make a contenteditable div perform tab spacing with a simple keystroke of the tab key

I've been trying to figure out how to make this contenteditable div add tab spacing when I press the tab key, but so far no luck. If anyone has a solution for this issue, please feel free to share. You can use an ID, class, or any other method to get it working. Thank you.

div[contenteditable]{
                display:inline-block;
                font-family:lucida console;
                font-size:12px;
                line-height:14px;
                white-space: pre;
                padding:5px;
                margin:0;
                min-width:200px;
                min-height:50px;
                height:auto;
                background:#fff;
                border:1px solid #000;
            }
<div contenteditable="true">dwdw wdw</div>

Answer №1

You have the ability to trigger a keydown event

I came across a function that positions the caret at the end of the text when the tab key is pressed. This functionality works seamlessly on various browsers.

For more details, take a look at this resource: contenteditable, set caret at the end of the text (cross-browser)

$('#test').on( 'keydown', function( e ) {
    if( e.which == 9 ) {
        e.preventDefault();
        $(this).html($(this).html() + "   ") 
        placeCaretAtEnd( document.querySelector('#test') );
    }
} );


function placeCaretAtEnd(el) {
    el.focus();
    if (typeof window.getSelection != "undefined"
            && typeof document.createRange != "undefined") {
        var range = document.createRange();
        range.selectNodeContents(el);
        range.collapse(false);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (typeof document.body.createTextRange != "undefined") {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(el);
        textRange.collapse(false);
        textRange.select();
    }
}
div[contenteditable]{
  display:inline-block;
  font-family:lucida console;
  font-size:12px;
  line-height:14px;
  white-space: pre;
  padding:5px;
  margin:0;
  min-width:200px;
  min-height:50px;
  height:auto;
  background:#fff;
  border:1px solid #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div contenteditable="true" id="test">asdfsadf</div>

Answer №2

Here is the code snippet for your reference

function keypress(ev){
 if(ev.keyCode==9){
   ev.target.innerHTML+=" " ;
   ev.preventDefault();
  }
}
div[contenteditable]{
  display:inline-block;
  font-family:lucida console;
  font-size:12px;
  line-height:14px;
  white-space: pre;
  padding:5px;
  margin:0;
  min-width:200px;
  min-height:50px;
  height:auto;
  background:#fff;
  border:1px solid #000;
}
<div contenteditable="true" onkeydown="keypress(event)">dwdw wdw</div>

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

Encountered a problem with AngularUniversal prerendering: UnhandledPromiseRejectionWarning: Unable to locate NgModule metadata for 'class{}'

Objective The task may seem lengthy, but it's straightforward! Currently, I am utilizing Angular Universal for Server-Side Rendering (SSR) by following a tutorial. The Universal/express-engine has been installed, main.js is generated in the dist/pro ...

What could be the reason for my CSS selector with :target not functioning properly?

I tried to implement the instructions I found online for using :target, but it's not working as expected. My goal is to change the background color and font color of #div1 when the first link is clicked, and to change the border of #div2 when the seco ...

Generating a JavaScript variable linked to a Rails Active Record relationship

I'm trying to implement an active record association in the DOM, but I'm encountering some difficulties. Here is my editor class: .editing .row .col-sm-3 .col-sm-8 .text-left #font-20 .title-font . ...

Having trouble locating the search bar element on Walmart's website?

I'm currently working on a bot that needs Selenium to interact with the search bar on Walmart's website, where it will input the name of a specific product and perform a search. However, I've encountered an issue where no matter what method ...

programming issue: unable to resolve

The issue at hand involves creating a function that can determine the presence of all the letters from the second element in the array within the first element. For example, when given the arguments ["hello", "hey"], the function should return false becaus ...

Creating a sticky menu in a column using affix with a CSS bootstrap list-group

My goal is to develop a sticky menu utilizing CSS Bootstrap affix and the list-group menu. I have successfully implemented most of it, except for one issue when the user scrolls down. Upon scrolling down, the menu expands to fill the entire width of the ...

Trouble with Next.js App Router OG Image not appearing after deployment

I am facing an issue with my Nextjs project that uses the app router. Inside the app directory, there is a file named opengraph-image.png. I have set this file to be the OG Image for the landing page, but after deploying and checking, the OG image does not ...

Finding the Determinant of a 4x4 Matrix: A Ray-Tracing Adventure in JavaScript

Currently, I am in the process of developing a raytracer using Javascript/Canvas and following "The Ray Tracer Challenge" by Jamis Buck. Initially, my code successfully computed the determinant of a 3x3 matrix but encountered issues with a 4x4 matrix. As a ...

The Jquery ajax page is redirecting automatically when a post request is made

Encountering an issue while attempting to upload multiple files through AJAX, as the process redirects to a blank page displaying only the names of the uploaded files. Here is the HTML tag: Below is the JavaScript function: function upload(){ var proje ...

Ensure that the "select" dropdown menu remains a constant size

One section of my Android app, powered by JQuery Mobile, displays a table with a combobox. The issue arises when selecting the option with a very long text, causing the combobox to expand and show half of the table off-screen. My goal is to set the combob ...

Issue with Three.js: The mouse hover effect does not revert back to the previous color

Currently, I am working on creating a pattern using Three.js. The goal is to change the color of a face to gray when the user hovers over it with the mouse, and then revert it back to its original light blue color when the mouse moves away. Unfortunately, ...

Fetching information from a data object using asyncData in Nuxt

Is there a method to retrieve object properties as keys from the asyncData() function? data() { return { bookmark_btn: { status: null, loading: false } } } I attempted to access data object properties in the following ...

A guide to generating numerous SVG paths using a JavaScript function

Creating strokes with similar length but different angles of rotations can be achieved efficiently using JavaScript instead of writing redundant lines of code. The following code snippet demonstrates one way to achieve this: function stroke(rot) { var d ...

What is the best way to center the image on a page?

How can I center an image on the screen with a caption? <div id="team-area"> <div class="container"> <div class="row"> <div class="col-12"> <h3 class="main-title">Our Team</h3> < ...

Is it possible to use the inheritance type for a function parameter derived from an object?

When working with Angular, I have been using TypeScript for some time now. Previously, I used to set function parameter types in a hardcoded way, as shown below: login(email: string) {} However, I recently tried to inherit from another object and changed ...

The dropdown menu displaying the img-dropdown-content with a display set to none is not functioning as anticipated

Attempting to hide drop down menu with img-dropdown-content but it's not working, possibly being overridden by another element - only using html and css I have experimented with visibility: hidden; both with and without !important as well as display: ...

Having issues with the CSS block in my Jekyll dropdown navbar

I have been exploring resources from both w3schools and another website to create a navigation bar in Jekyll using frontmatter. However, I am running into issues with the block property in CSS. Most of the navbar is functioning properly, except for the dro ...

Can PHP and AJAX conflict and insert the same query twice?

Currently, I am in the process of creating a simple chat box using PHP, PDO, and AJAX. However, I have encountered an issue where after incorporating the AJAX code, when I submit my shout it seems to run the query twice. I have thoroughly checked my code w ...

Updating the global CSS styles that were inherited from the node_modules folder in a Next.js project

I've been attempting to customize the CSS style for a rc-pagination component that was included in a CSS file I already imported in the root component _App. However, despite my efforts to override the styles in the index.css file of this component, no ...

Responsive input form causes floating label to be positioned incorrectly

I have crafted a form using Django, Crispy Forms, and Bootstrap. When the screen width is above 575px, everything looks great with fields of appropriate width and floating labels in their correct position. However, when the screen width drops below 575px, ...