Incorporate a caret into an element using CSS styling

issue

I encountered an issue where <textarea> and Javascript had some quirks when trying to transfer the value into a <pre> tag. My aim was to implement a blinking caret in the <pre> as if I were pressing F7. The reason behind not using just the <textarea> is because I am currently working on a JSON formatter project with added syntax highlighting for entertainment purposes.

current setup

document.querySelector("pre.stuff").addEventListener("click", function() {
  document.querySelector("textarea.text").focus();
});
document.querySelector("textarea.text").addEventListener("input", function() {
    document.querySelector("pre.stuff").innerText = this.value;
});
textarea.text {
  position: absolute;
    border: none;
  padding: 0px;
  opacity: 0;
  width: 0px;
  height: 0px;
}
pre.stuff {
    width: calc(100% - 20px);
    height: 250px;
    border: solid gray 2px;
    margin: 0px;
    border-radius: 5px;
    padding: 10px;
    transition: 0.3s;
    font-family: "Source Code Pro", monospace;
    tab-size: var(--tab-size);
    overflow: scroll;
    cursor: text;
}
textarea.text:focus ~ pre.stuff, pre.stuff:focus {
    outline: none;
    box-shadow: #0066ff55 0px 0px 0px 4px; /* glowwww */
    border: solid #66a3ff 2px;
}
body {
    margin: 16px;
}
<link href="https://fonts.googleapis.com/css2?family=Source+Code+Pro&display=swap" rel="stylesheet">
<textarea class="text"></textarea>
<pre class="stuff" spellcheck="false" tabindex="-1"></pre>
<br>
I decided to exclude the syntax highlighting aspect :P

In addition, it's crucial for the focus to remain on the <textarea> for the functionality to properly work.

Answer №1

To achieve this effect, you will need to use an absolutely positioned element as a caret because the textarea element does not have a built-in property to manipulate the caret position. You'll have to create custom events to track changes in the textarea value. Here is an example of how you can implement this:

Please keep in mind that you can disable the caret transition if it's distracting. Also note that for this demonstration, I'm utilizing a library available at this link

const txtarea = document.querySelector("textarea.text");
        const invis = $('#faux');


        document.querySelector("pre.stuff").addEventListener("click", function() {
          document.querySelector("textarea.text").focus();
        });
        document.querySelector("textarea.text").addEventListener("input", function() {
            document.querySelector("pre.stuff").innerText = this.value;
        });

        txtarea.addEventListener("keyup", move_caret);
        txtarea.addEventListener("keydown", move_caret);


        function move_caret() {
            let select = document.getSelection();
            let index = txtarea.selectionStart;

            let background = getComputedStyle(txtarea).color;

            const editor = $("textarea.text");
            let pos = editor.caret('position');
            let left = pos.left + 2 + "px";
            let top = pos.top + 2 + "px";
            let height = pos.height + "px";
            var css_data = {
                left,
                top,
                height,
                background
            };
            $("#caret").css(css_data);

        }
* {
            position: relative;
        }
        textarea.text {
            min-width: calc(100% - 20px);
            word-wrap: nowrap;
            height: 250px;
            border: solid gray 2px;
            margin: 0px;
            border-radius: 5px;
            padding: 10px;
            transition: 0.3s;
            font-family: "Source Code Pro", monospace;
            tab-size: var(--tab-size);
            overflow: scroll;
            cursor: text;
            opacity: 0;
            pointer-events: none;
            position: absolute;
        }
        pre.stuff {
            max-width: calc(100% - 20px);
            word-wrap: break-word;
            height: 250px;
            border: solid gray 2px;
            margin: 0px;
            border-radius: 5px;
            padding: 10px;
            transition: 0.3s;
            font-family: "Source Code Pro", monospace;
            tab-size: var(--tab-size);
            overflow: scroll;
            cursor: text;
        }
        textarea.text:focus ~ pre.stuff, pre.stuff:focus {
            outline: none;
            box-shadow: #0066ff55 0px 0px 0px 4px; /* glowwww */
            border: solid #66a3ff 2px;
        }
        body {
            margin: 16px;
        }


        #caret {
            width: 2px; 
            display: inline; 
            position: absolute;

            transition: left 137ms linear, top 137ms linear;
            animation: blink 450ms linear alternate infinite;
        }

        @keyframes blink {
            0% {opacity: 0;}
            20% {opacity: .5;}
            75% {opacity: .78}
            100% {opacity: 1}
        }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Caret.js/0.3.1/jquery.caret.min.js" integrity="sha512-qclRGh1kwCdmGsi68M9XYAhbCC4xpGRq9VqVlYAQmsG29wQG0DKke/QiMFmuFY1NGXdJ75Wjkhez5nMcuTelgQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<div id="caret"></div>
    <span id="faux" style="display:none"></span>
    <link href="https://fonts.googleapis.com/css2?family=Source+Code+Pro&display=swap" rel="stylesheet">
    <textarea class="text"></textarea>
    <div style="display: inline; width: min-content; height: min-content;">
        <pre class="stuff" spellcheck="false" tabindex="-1"></pre>
        
    </div>
    <br>

Answer №2

Issue Resolved!

I managed to solve the problem by adjusting the dimensions of the <textarea> to match those of the <pre>, setting the text color to transparent and the caret color to black. I also eliminated the border and made some additional tweaks, which surprisingly did the trick! Although it's a bit of a workaround, matching the font size and family with the <pre> tag worked perfectly.

Check it out below

document.querySelector("pre.stuff").addEventListener("click", function() {
  document.querySelector("textarea.text").focus();
});
document.querySelector("textarea.text").addEventListener("input", function() {
    document.querySelector("pre.stuff").innerText = this.value;
});
/* CSS code here */
<link href="https://fonts.googleapis.com/css2?family=Source+Code+Pro&display=swap" rel="stylesheet">
<textarea class="text"></textarea>
<pre class="stuff" spellcheck="false" tabindex="-1"></pre>
<br>
I removed the syntax highlighting part :P

It may not be flawless, but it serves its purpose for me.

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

Managing and authenticating HTML checkboxes using Spring MVC controller

Currently working with Spring MVC and designing a user registration page. I want to provide users with the choice to opt-in for email notifications and agree to Terms of Service before signing up. Due to using Thymeleaf as my templating engine, I am facing ...

Illuminate the expanded dropdown menu in a Bootstrap 5 navbar

Bootstrap 5 navbar allows for the creation of dropdown menus. Is there a way to highlight the current menu item when a dropdown is opened, similar to how it's done in Windows desktop applications? This feature is not provided by Bootstrap 5: https:/ ...

Ways to speed up the disappearance of error messages

There is a minor issue that I find quite annoying. The validation error message takes too long (approximately 3 seconds) to disappear after a valid input has been entered. Let me give you an example. https://i.sstatic.net/8UKrm.png Do you have any tips o ...

Combine the elements within the HEAD tag into a group

I am currently developing a dynamic page system using AJAX. Whenever a link is clicked, an AJAX call is made to retrieve data from the requested page. However, I have encountered an issue where certain data in the page file needs to be placed within the h ...

Combine and interchange horizontal and vertical form designs within antd 5 for a personalized touch

I need to customize the layout of a form to display checkboxes in vertical mode. Specifically, there is a row of checkboxes that I want to appear vertically aligned rather than horizontally. In the past, I was able to achieve this in antd 4 by applying a ...

Generating a dataframe with cells that have a combination of regular and italicized text using the sjPlot package functions

I've been trying to set up a basic data table where the genus name in the "Coral_taxon" column is italicized, but the "spp." part following it remains lowercase. I thought of using the expression() function for each row in "Coral_taxon," but so far, I ...

The sub-menu is being obscured by a PDF element in Internet Explorer, causing visibility issues

I have an object type tag on my page that displays a PDF file. Everything is functioning correctly, but in Internet Explorer, my sub-menu is being hidden behind the object tag. var objTag = $('<object></object>') .attr({ data: source ...

The clickable area for the radio button cursor is too large

As I embark on my journey with HTML and CSS, I have encountered two issues while creating a form: The spacing between the question and answers is too wide. The second picture depicts how I would like it to appear. The cursor:pointer seems to be extending ...

Struggling to get custom button hover styles to work in React?

In the React project I'm working on, there is a button that has been configured in the following manner. <label style={styles.label}> <input style={styles.input} type="file" accept="image/*" onChange={this.onUpload} /& ...

A chatbot developed with deep learning algorithms and powered by Flask was designed to interact with users. However, one of its

My project involves creating a chatbot using a deep learning model and Flask. I have encountered an issue where the bot is not responding and displays the following error message: GET /run?msg=salut HTTP/1.1" 404 - This snippet contains the HTML code: ...

How can objects be positioned or moved in a linear fashion, and how to incorporate free fall when adding additional objects?

I'm interested in creating a system similar to a "vibrating table" with linear displacement. After studying various tutorials, I was able to achieve simulations based on the following examples: Following the tutorial "Authoring a Multibody Simulatio ...

Animating an image inside a bordered div

I'm attempting to create an animated effect where an image moves randomly within the boundaries of a div container. While I've come across solutions for animating within borders, none have specifically addressed keeping the image inside the div. ...

Sliding panels with Jquery

I've created some basic panels that slide in and out horizontally. My goal is to hide all content except the first panel when the page loads. When a link to other panels is clicked, the current content will slide left to be hidden and new content will ...

Discovering the presence of line breaks

I have searched extensively on Google, but I am struggling to find a definitive answer. My goal is to create an email simulation where users can input text into a textarea and save it to the database. They should then be able to return to the page later a ...

Restricting HTML Code within a DIV Container

I am currently developing a plugin and widget-centric CMS system. In this setup, a widget consists of a snippet of HTML/JavaScript code that is contained within a main div element known as the widget div. For JavaScript frameworks, I have opted to use jQ ...

The division element shifts to the left upon invoking the slideUp() function

I am currently working on a page that contains a form with two different sections - one is visible and the other is hidden. When the user clicks a button in the first section, it slides up using slideUp() while the hidden section slides down using slideDow ...

I am trying to connect HTML input with Python but I am not sure how to do it

As part of our capstone course team project, we are developing a self-hosted calendar app specifically designed for college students. One of our team members has taken the initiative to create HTML webpages for this self-hosted server. My current task is t ...

Connections between Wordpress websites and CSS styling

My inquiry consists of three parts: I am currently in the process of constructing a portfolio website using Wordpress, and I have encountered some peculiar links. For instance, on my about page, the link appears as localhost/AFolder/anotherfolder/ind ...

Executing a parent window function from a child window using AngularJS

I'm working on a multi-page/window application where a dashboard page controls a list of children (windows). The dashboard should be able to call functions in the children and vice versa. However, I'm facing an issue where the child fails to invo ...

The webpage Page.php is failing to display the newly added content

I have a collection of logos on my homepage (index.php) in WordPress, and they are positioned at the bottom just as I intended. However, these logos do not appear on all pages. Even if I add the exact same code to the page.php file in the exact position, ...