Identifying stylized text in contenteditable while navigating with arrow keys

Hello there! I am looking for a way to identify the text format within my editable div using arrow keys and automatically highlight the corresponding formatting buttons.

For instance, if my cursor is on the phrase "This is me" and it is bold, strikethrough, and colored, I want the bold, strikethrough, and font color buttons to be highlighted. How can I achieve this functionality?

I would greatly appreciate any assistance.

Thank you!

$(function () {
    $('#editor').on('keydown', function (event) {
        if (
            event.keyCode == 37 // left arrow key pressed
            || event.keyCode == 38 // up arrow key pressed
            || event.keyCode == 39 // right arrow key pressed
            || event.keyCode == 40 // down arrow key pressed
        ) {
            // code implementation here ...
        }
    });
});
ul li {
    display: inline-block;
}
.btn-decorations .btn-color {
    display: block;
    width: 18px;
    height: 18px;
    border-radius: 2px;
    position: relative;
}
.btn-color-blue {
    background-color: blue;
}

.btn-color-red {
    background-color: red;
}

.btn-color-black {
    background-color: black;
}

.on {
    border: 3px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
    <p id="editor" contenteditable="true"><font><strike><b>This is me.</b></strike></font> Some test text for you to select</p>
</div>
<div class="btn-area btn-area-center">
    <ul class="btn-decorations">
        <li>
            <button type="button" class="btn-ic on" id="addBold">
                <svg xmlns="http://www.w3.org/2000/svg" width="13" height="17" viewBox="0 0 13 17">
                    <g id="ic-bold" class="ic-bold" transform="translate(-5.5 -3.5)">
                        <path id="path-1" class="path-1" data-name="path-1" d="M6,4h7.333A3.844,3.844,0,0,1,17,8a3.844,3.844,0,0,1-3.667,4H6Z" transform="translate(0)" fill="none" stroke="#777" stroke-linecap="round" stroke-linejoin="round" stroke-width="1"/>
                        <path id="path-2" class="path-2" data-name="path-2" d="M6,12h8.308A3.855,3.855,0,0,1,18,16a3.855,3.855,0,0,1-3.692,4H6Z" transform="translate(0)" fill="none" stroke="#777" stroke-linecap="round" stroke-linejoin="round" stroke-width="1"/>
                    </g>
                </svg>
            </button>
        </li>
        <li>
            <button type="button" class="btn-ic on" id="addStrike">
                <svg xmlns="http://www.w3.org/2000/svg" width="12.5" height="16.5" viewBox="0 0 12.5 16.5">
                    <g id="ic-strike" class="ic-strike" data-name="ic-strike" transform="translate(-13.46 -4.751)">
                        <path id="path-1" data-name="path-1" d="M25.469,12.743H19.731a7.047,7.047,0,0,1-2.227-.827A3.9,3.9,0,0,1,16.28,10.8a3.047,3.047,0,0,1-.524-1.76...
            

Answer №1

Let's consider the following scenario.

$(function() {
  $('#editor').on('keydown', function(event) {
    if (event.keyCode >= 37 && event.keyCode <= 40) {
      var el, active = [];
      if (document.selection) {
        el = document.selection.createRange().parentElement();
      } else {
        el = window.getSelection().anchorNode.parentNode;
      }
      while ($(el).prop("nodeName") != "P") {
        active.push($(el).prop("nodeName"));
        el = $(el).parent().get(0);
      }
      console.log(active.join(", "));
    }
  });
});
ul li {
  display: inline-block;
}

.btn-decorations .btn-color {
  display: block;
  width: 18px;
  height: 18px;
  border-radius: 2px;
  position: relative;
}

.btn-color-blue {
  background-color: blue;
}

.btn-color-red {
  background-color: red;
}

.btn-color-black {
  background-color: black;
}

.on {
  border: 3px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <p id="editor" contenteditable="true">
    <font><strike><b>This is me.</b></strike></font> Some test text for you to select</p>
</div>
<div class="btn-area btn-area-center">
  <ul class="btn-decorations">
    <li>
      <button type="button" class="btn-ic on" id="addBold">
                                        <svg xmlns="http://www.w3.org/2000/svg" width="13" height="17" viewBox="0 0 13 17">
                                            <g id="ic-bold" class="ic-bold" transform="translate(-5.5 -3.5)">
                                                <path id="path-1" class="path-1" data-name="path-1" d="M6,4h7.333A3.844,3.844,0,0,1,17,8a3.844,3.844,0,0,1-3.667,4H6Z" transform="translate(0)" fill="none" stroke="#777" stroke-linecap="round" stroke-linejoin="round" stroke-width="1"/>
                                                <path id="path-2" class="path-2" data-name="path-2" d="M6,12h8.308A3.855,3.855,0,0,1,18,16a3.855,3.855,0,0,1-3.692,4H6Z" transform="translate(0)" fill="none" stroke="#777" stroke-linecap="round" stroke-linejoin="round" stroke-width="1"/>
                                            </g>
                                        </svg>
                                    </button>
    </li>
    <li>
      <button type="button" class="btn-ic on" id="addStrike">
                                        <svg xmlns="http://www.w3.org/2000/svg" width="12.5" height="16.5" viewBox="0 0 12.5 16.5">
 <!-- More SVG Code Here -->
                                    </button>
    </li>
    <li>
      <button type="button" id="addColorBlack" class="btn-add-color on">
 <!-- More Button Code Here -->
                                    </button>
    </li>
    <li>
      <button type="button" id="addColorBlue" class="btn-add-color">
 <!-- More Button Code Here -->
                                    </button>
    </li>
    <li>
      <button type="button" id="addColorRed" class="btn-add-color">
 <!-- More Button Code Here -->
                                    </button>
    </li>
  </ul>
</div>

This elaborates on the solution provided in How to detect when a child-element of a contenteditable DIV is edited via keyboard?

In case of arrow key input, it is essential to verify if the parent element is P. If not, an iteration through each parent element is required to determine the applied elements on the Text Node.

Upon identifying these elements, appropriate buttons can be highlighted accordingly.

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

Interact with scrollable tabs on your mobile device with ease

I'm currently working on creating touch scrollable tabs using Bootstrap 4, specifically for mobile view. I attempted to modify a Bootstrap 3 code snippet found at to work with Bootstrap version 4. You can find the Codepen demo here: https://codepen. ...

Choosing between Ajax and Websockets for sending small amounts of dataOR

I am currently developing a chat website that utilizes Websockets (Socket.io) to facilitate communication between users and the server. While Websockets are essential for sending and receiving messages in real-time, I am facing a challenge when it comes to ...

Is it possible to use CSS and HTML to rotate a cube and expand its sides?

I am attempting to rotate the cube and expand its faces. I have experimented with the following code: .wrapper{ position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); } .cube-wrap { width: 40px; height: 40px; ...

Axios delivers the index.html data to the front end of a React.js application

I’m currently in the process of developing a web application using React.js for the front-end and Flask for the back-end. I attempted to establish a connection between the two by defining a proxy server in React and enabling CORS in Flask. Everything was ...

AngularJS allows for setting the rate value using the jQuery Raty plugin

I am attempting to implement the jquery raty plugin for star rating using angularjs. To achieve this, I have created a custom directive as shown below: app.directive("ngStars", function() { return { restrict: 'A', ...

Adding images to HTML using JavaScript below existing images

I'm currently working on a JavaScript game and I want to implement a feature where my character can move under blocks (isometric PNG images) instead of just sliding through them. Is there a way to dynamically adjust my character's position in the ...

When you hover over it, the text moves above the background content

I am looking to enhance my table by having the text expand and hover over the content with a white background. I have achieved the expand effect, but I am struggling to get the overflow to work properly. You can view the code in action on JsFiddle: JsFiddl ...

What is the best way to break a single line into multiple lines when working in VS code?

I have written the following code in nodeJS.. async function GetSellerInfoByID({seller_user_id}) { console.debug("Method : GetSellerInfoByID @user.service.js Calling..."); await clientDB.connect(); dataBaseData = await clientDB. ...

Transforming a CSV file into JSON format using Gatsbyjs

I am currently exploring the possibilities of GatsbyJs and considering the utilization of the gatsby-transformer-csv plugin. You can find the documentation for this plugin here. I have got my hands on two CSV files exported from WordPress that I am eager ...

creating a dynamic bounce animation using jqueryui and svg

I am trying to manipulate an SVG file using JQUERYUI. Effects like slide in show and hide are working fine, but I am having trouble with the bounce effect. Does anyone have any ideas on how to achieve this? Here is my jQuery function: $('#logo' ...

Create a visual layout showcasing a unique combination of images and text using div elements in

I created a div table with 3 images and text for each row, but I'm struggling to make all the text-containing divs uniform in size. How can I achieve this? Also, I need to center this table on the screen, and currently using padding to do so. Is there ...

Populating the table with data through a repetitive process

Is there a way to automatically populate a table using values from an array? <table> <thead> <tr> <div ng-repeat="n in range" > <th> {{vm.data.list[n].temp.day}} {{vm.symbal}} ...

What is the best way to ensure these 2 divs are aligned vertically in the provided html (starting at the same vertical level)?

<div class="container"> <div class="row"> <div class="col-lg-12"> <div class="news-title"> <h3 class="title">NEWS & ARTICLES</h3> ...

Javascript textbox and submit button

Is there a way to generate a text box with a submit button and save the input into a JavaScript variable? ...

On mobile devices, the alignment of text in Bootstrap doesn't appear as intended

I'm creating a portfolio website for showcasing my design projects from university. The text in the "my work" section is centered, but it seems misaligned with other elements like buttons when the window width is reduced. What could be the issue? Cod ...

Is it possible to invoke a server-side Groovy object method from client-side JavaScript using AJAX?

Although I find that DWR meets my Java needs, I am curious if there is a more Groovier approach to achieving the same objective - one that leverages convention over configuration, dynamic method invocation, and other advanced techniques. ...

Can JS variables be recycled in any manner?

I'm currently working on building a simplified version of an online citation generator. This project involves creating over 20 input boxes, each requiring the user to enter an author's name. To streamline this process, I've divided the autho ...

The client.postMessage() function in a service worker is not being recognized by the onmessage handler within an AngularJS controller

Handling Service Worker Messages: let angularClient; self.addEventListener('message', function(event) { // store the client that sent the message in the angularClient variable angularClient = event.ports[0]; }); Service Worker Notificat ...

Unable to select div element by clicking on the text

I'm currently working on automating downloads for my employer. I'm using selenium with python and chromedriver. However, I've hit a roadblock when trying to click on a div element as part of a javascript drop down menu. <div class="item ...

The Chrome browser allows interaction between two separate divs, where a button located in one div can impact

One issue I encountered involves a button located within a div that has unintended consequences for another div. Here is the basic structure of the elements: <div> <div> <div> <div> <butto ...