Clicking on the checkbox will remove the selected text within the contenteditable div

My objective is to create a custom text editor with basic functionalities such as bold, italic, underline, and paragraph styling only. The purpose of this project is for studying purposes.

The main challenge I am facing is avoiding color-based interactions through JavaScript and utilizing color interaction via CSS only. Hence, I am aiming to achieve this using pure JS & CSS without any external library.

To implement this, I have utilized a checkbox element to toggle bold font within a contenteditable div. However, the issue arises when the checkbox clears the selection in HTML before obtaining the range of the selected text from div.innerHTML. How can I resolve this dilemma?

function actionBold122(e){

    let editor = document.getElementById('editor')

    let input = e.getElementsByTagName('input')[0]

    if(input != null){
        input.checked = !input.checked
    }

    var html = "";
    if (typeof window.getSelection != "undefined") {
        var sel = window.getSelection();
        if (sel.rangeCount) {

            var arr  = []
            for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                arr.push(sel.getRangeAt(i).cloneContents().textContent);
            }
            html = arr.join();
        }
    } else if (typeof document.selection != "undefined") {
        if (document.selection.type == "Text") {
            html = document.selection.createRange().htmlText;
        }
    }


    alert(html)

}
input{

    display: none;
}

input:checked+svg{

    background-color: rgb(194, 10, 10);
    fill: #fff;
}

label{

    cursor: pointer;
}


#editor{

    width: 50%;
    min-height: 40px;
    background-color: antiquewhite;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test</title>
</head>
<body>

    <label onclick="actionBold122(this); return false">
        <input class="none" type="checkbox" name="0" checked>
         <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M15.6 10.79c.97-.67 1.65-1.77 1.65-2.79 0-2.26-1.75-4-4-4H7v14h7.04c2.09 0 3.71-1.7 3.71-3.79 0-1.52-.86-2.82-2.15-3.42zM10 6.5h3c.83 0 1.5.67 1.5 1.5s-.67 1.5-1.5 1.5h-3v-3zm3.5 9H10v-3h3.5c.83 0 1.5.67 1.5 1.5s-.67 1.5-1.5 1.5z"/><path d="M0 0h24v24H0z" fill="nonext/html"></svg>
     </label>

    <div id="editor" contenteditable>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Enim omnis ea, voluptas maxime perspiciatis praesentium magni repellendus earum suscipit sint. Veritatis fuga adipisci accusantium similique distinctio vero tenetur ipsam fugiat.</p>
    </div>
    <button onclick="actionBold122(this)">Get Text</button>
</body>
</html>

Current code:

https://i.sstatic.net/6l39l.gif

I aim to achieve similar functionality to the "Get Text" button with the checkbox input. If you have any ideas on how to address this issue, please feel free to suggest. Thank you in advance!

Answer №1

In case you're facing the issue of losing focus when clicking on the input field, resulting in the text becoming unselected, one solution could be to store the selected text in a variable. Here's an example:

Consider the following code snippet:

function actionBold122(e){

    let editor = document.getElementById('editor')

    let input = e.getElementsByTagName('input')[0]

    if(input != null){
        input.checked = !input.checked
    }

    alert(selectedText);

}

var selectedText = '';

function onMouseUp() {
    const sel = window.getSelection();
    var arr  = []
    for (var i = 0, len = sel.rangeCount; i < len; ++i) {
        arr.push(sel.getRangeAt(i).cloneContents().textContent);
    }
    selectedText = arr.join();
}
input{

    display: none;
}

input:checked+svg{

    background-color: rgb(194, 10, 10);
    fill: #fff;
}

label{

    cursor: pointer;
}


#editor{

    width: 50%;
    min-height: 40px;
    background-color: antiquewhite;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test</title>
</head>
<body>

    <label  onclick="actionBold122(this); return false">
        <input class="none" type="checkbox" name="0" checked>
         <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M15.6 10.79c.97-.67 1.65-1.77 1.65-2.79 0-2.26-1.75-4-4-4H7v14h7.04c2.09 0 3.71-1.7 3.71-3.79 0-1.52-.86-2.82-2.15-3.42zM10 6.5h3c.83 0 1.5.67 1.5 1.5s-.67 1.5-1.5 1.5h-3v-3zm3.5 9H10v-3h3.5c.83 0 1.5.67 1.5 1.5s-.67 1.5-1.5 1.5z"/><path d="M0 0h24v24H0z" fill="none"/></svg>
     </label>

    <div onmouseup="onMouseUp()" id="editor" contenteditable>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Enim omnis ea, voluptas maxime perspiciatis praesentium magni repellendus earum suscipit sint. Veritatis fuga adipisci accusantium similique distinctio vero tenetur ipsam fugiat.</p>
    </div>
    <button  onclick="actionBold122(this)">Get Text</button>
</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

Guide to retrieving and editing images from Appwrite using Vue

Currently, I am utilizing a View frontend to retrieve a PDF file from Appwrite Storage. My goal is to acquire the PDF, insert additional text onto it, and then save it to the user's local device. Below is the code I have so far - although I can recei ...

Is there an alternative to the jQuery :contains selector?

How can I choose an option from a drop-down menu based on its text value? When I execute the following code: var desiredText = "Large"; $("#size option:contains(" + desiredText + ")").attr('selected', 'selected'); it ends up selecting ...

What could be causing the "Failed prop type" error when dealing with nested cloned children, despite the parent having the correct initial values

Here is a question with two parts: What causes prop types checks to fail in a react-only scenario? How does a material-ui HoC interfere with type checking? When creating UI components, I keep the children unaware of each other by passing props through R ...

Extracting data from websites using Python's Selenium module, focusing on dynamic links generated through Javascript

Currently, I am in the process of developing a webcrawler using Selenium and Python. However, I have encountered an issue that needs to be addressed. The crawler functions by identifying all links with ListlinkerHref = self.browser.find_elements_by_xpath( ...

Troubleshooting the Ui-router refresh problem

I set up my ui-router configuration as follows: app.config(function($stateProvider, $urlRouterProvider, $locationProvider) { $stateProvider .state('home', { url: "/home", templateUrl : 'h ...

Center the radio buttons regardless of the length of the text

My dilemma lies with 3 radio buttons and their corresponding labels - while 2 of them are aligned perfectly beneath each other due to their matching character lengths, the middle one extends further making it look misaligned. Check out this fiddle. Below ...

What is the best way to mark a specific photo as a favorite in an array of Photo objects?

I am working with a basic array of photo categories that follows this structure: [ { category: 1001, photos: [ { id: 100101, url: 'url.com/100101', favorite: false}, { id: 100102, url: 'url.com/100102', favorite: ...

Issue with a Jquery toggleClass function not working properly on hover

Hello everyone! I am a newbie in the community and relatively new to the world of web programming. I am encountering an issue that is really frustrating me. I attempted to use this code to add a class when hovering over the ul list element so that I can d ...

Can Selenium successfully scrape data from this website?

I am currently attempting to extract Hate Symbol data (including the name, symbol type, description, ideology, location, and images) from the GPAHE website using Selenium. As one of my initial steps, I am trying to set the input_element to the XPATH of the ...

What is the best way to send the value of a Select component from a child to a parent component in

Users have the ability to select a category, triggering the appearance of another dropdown menu based on their selection. I have created a separate component in a different file (.js) to handle this second dropdown. While I can see the data, I am wondering ...

Code functioning properly on JS Fiddle, experiencing difficulties when running directly in browser

Hey there, I have this vertical jquery tabs example working on JSFiddle, you can check it out here: https://jsfiddle.net/tj_vantoll/nn2Qw/ I've been trying to replicate it in an HTML file but so far I haven't had any luck... Can someone help me ...

Embed a subcomponent within another component triggered by an onClick event in ReactJS

Watch this quick demo to see my project in action. So, here's the deal - I have a menu with different options, and when "Tickers" is selected, I want it to display the Tabs component. However, if any other menu option is chosen, I don't want the ...

Optimizing Divs for Maximum Layout Efficiency

My current issue involves a series of divs that contain varying amounts of content. These divs are floated left and I am striving to align them seamlessly without any vertical space between them (except for the 10px margin that I have included). You can v ...

The three.js raycaster is able to detect objects both in front of and behind the specific object I am trying to select

I am currently working on rendering a 3D model of a house using Three.js and encountering an issue with the raycaster in my code. The problem I'm facing is that it's selecting every object both behind and in front of the specific object I want to ...

What is the best way to clear an XML or table?

As I delve into learning Javascript, I've been experimenting with different approaches to achieve a specific functionality. I'm trying to implement a button that can toggle or hide XML data in a table. My attempts so far have involved adding anot ...

"When working with Vue projects, an error may occur stating "Parsing error: No babel config file detected" if the IDE is not opened at

Encountered an issue in VS Code with a Vue project, where if the project is not opened at the root directory, babel.config.js fails to load causing confusion for the IDE. https://i.sstatic.net/pupVh.png All my files display an error on the initial charact ...

Using v-model with checkboxes in vue.js: A Step-by-Step Guide

How can I use a checkbox with a v-model in Vue2.js? <input type="checkbox" value="test" :checked="selected"/> I need the value of the checkbox to be test, and I also require two-way binding with the prop named selected, ...

having difficulty accessing the value within the Angular constructor

My current issue arises when I click on a button and set a value within the button click method. Despite declaring the variable in the constructor, I am unable to retrieve that value. The code snippet below demonstrates this problem as I keep getting &apos ...

Incorporation of a dynamic jQuery animation

I'm a beginner in jquery and I'm attempting to achieve the following: I want each menu to collapse separately when the mouse hovers over it. The issue is that both menus collapse simultaneously! I know it's probably something simple, but I ...

Transmission of state modifications in React

My React project is organized with the following hierarchy: The main A component consists of child components B and C If I trigger a setState function in component B, will components A and C receive notification and potentially re-render during the recon ...