Add a CSS class to the text that is selected within a Content Editable div

Hey there, I'm having an issue where the class is being applied to the button when pressed instead of the selected text. Here's my current code:

The button needs to be a div, but it might be causing the problem. I just want the highlighted text to receive the class, not the button itself.

Cheers...

function addAnimation() {
  document.execCommand('formatblock', false, 'span');
  selectedElement = window.getSelection().focusNode.parentNode;
  selectedElement.className += "grad";
}
.textField {
  background: #333;
  color: #fff;
  width: 300px;
  height: 300px;
}

.grad {
     -webkit-animation: changeColor 8s ease-in infinite;
   animation: changeColor 8s ease-in infinite;
}

@-webkit-keyframes changeColor {
  0% {color: #ff7473;}
  25% {color: #ffc952;}
  50% {color: #fc913a}
  75% {color: #75D701;}
  100% {color: #ff7473}
}
<div class="textField" contenteditable="true">Hello world. Select this text and press the button</div>

<div onclick="addAnimation()">Animate
            </div>

Answer №1

After pressing the virtual button, the selection disappears. To achieve this behavior, you must attach an event listener to the mousedown event in the following manner:

function addAnimation() {
    selectedElement = window.getSelection().focusNode.parentNode;
    $(selectedElement).addClass('grad');
}
$('.animate-selected').on('mousedown', addAnimation);
.text-field {
    background: #333;
    color: #fff;
    width: 300px;
    height: 100px;
}

.grad {
    -webkit-animation: changeColor 8s ease-in infinite;
    animation: changeColor 8s ease-in infinite;
}

.animate-selected{
    margin: 2px 0;
    border: 1px solid blue;
    display: inline-block;
    padding: 0 4px;
    cursor: pointer;
}

@-webkit-keyframes changeColor {
    0% {
        color: #ff7473;
    }
    25% {
        color: #ffc952;
    }
    50% {
        color: #fc913a
    }
    75% {
        color: #75D701;
    }
    100% {
        color: #ff7473
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text-field" contenteditable="true">
    Hello world. Select this text and press the button
</div>
<div class="animate-selected">
    Animate
</div>

You can also find it on JSFiddle.

If you only want to animate the selected text, follow these steps:

function addAnimation() {
    $('.grad').contents().unwrap(); /* this removes previous animation */
    var selectedText = window.getSelection();
    var container = $(selectedText.anchorNode.parentNode);
    var wrappedText = '<span class="grad">' + selectedText + '</span>'
    container.html(container.html().replace(selectedText, wrappedText));
}
$('.animate-selected').on('mousedown', function(e) {
    addAnimation();
});
.text-field {
    background: #333;
    color: #fff;
    width: 300px;
    height: 100px;
}

.grad {
    -webkit-animation: changeColor 8s ease-in infinite;
    animation: changeColor 8s ease-in infinite;
}

.animate-selected{
    margin: 2px 0;
    border: 1px solid blue;
    display: inline-block;
    padding: 0 4px;
    cursor: pointer;
}

@-webkit-keyframes changeColor {
    0% {
        color: #ff7473;
    }
    25% {
        color: #ffc952;
    }
    50% {
        color: #fc913a
    }
    75% {
        color: #75D701;
    }
    100% {
        color: #ff7473
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text-field" contenteditable="true">
    Hello world. Select this text and press the button
</div>
<div class="animate-selected">
    Animate
</div>

You can also view it on JSFiddle.

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

Update the styling for the second list item within a specified unordered list class instantaneously

Looking to emphasize the second list item (li) within a selected dropdown list with a designated unordered list class of "chosen-results". <div class="chosen-container chosen-container-single select-or-other-select form-select required chosen-proc ...

The session becomes obsolete when redirecting back to the previous page

When attempting to redirect using the http referrer after storing a value in Session in php, I noticed that the Session becomes null. Is there a method to maintain the session even when utilizing the http referrer? ...

Problem with user scalability in desktop browsers: when zooming out to 33% and lower, all CSS vanishes

Having trouble understanding why my styling disappears at 33% zoom on Chrome and even worse at 75% on IE11. <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1"> <meta name="viewport" content="w ...

When working with a set of objects, consider utilizing jQuery's InArray() method to effectively handle

Within my Javascript code, I am working with an array of Calendar objects. Each Calendar object contains an array of CalendarEvent objects. Every CalendarEvent object holds properties for Date and Name. I am looking to determine if a specific date exist ...

The function service.foo is not recognized in Angular

My service function is not being recognized by my component import { Injectable } from '@angular/core'; import { ToastController } from '@ionic/angular'; @Injectable({ providedIn: 'root' }) export class LocationService { ...

Switch back JSON in php script

After receiving a JSON object with an unspecified number of key/value pairs, I need to send it from my $.ajax function to a PHP script. The PHP script must then revert the JSON object and send it back to jQuery. {"First name": "John", "Contact": "2323",.. ...

Steps to hide a div with jQuery when a user clicks outside of a link or the div itself:1. Create a click event

Here's a simple question - I have a link that when clicked, displays a div. If the user clicks away from the link, the div is hidden, which is good. However, I don't want the div to be hidden if the user clicks on it. I only want the div to disap ...

Tips for showcasing a "loading" animation as a lazy-loaded route component loads

Utilizing webpack's code splitting feature, I have divided my application into multiple chunks to prevent the entire bundle from being downloaded at once when a user visits my website. Some routes require large chunks that may take some time to downl ...

Tips for integrating v-virtual-scroll with v-table?

My Vuetify table is handling a large amount of data – 300 rows with 20 columns, some of which have calculated rowspans. To improve performance, I'm considering using the v-virtual-scroll component. I came across this sample code, which doesn't ...

Wordpress fails to produce results when using Ajax and Jquery

I have encountered an issue with my code. It works perfectly fine outside of WordPress, but when I try to integrate it into a WordPress environment, the Ajax part fails consistently. Below is how I include jQuery and Ajax in WordPress: function transtatus ...

Is there a way to keep Angular from automatically re-sorting my list when I make edits to it?

I have designed a small application with Angular for managing Todolists. Each list contains multiple todos, where each todo has attributes such as name, value1, and value2. To automatically sort each list using Angular, I utilized ng-repeat="todo in selec ...

Reading data from a Node PassThrough stream after writing has finished can be achieved by piping the stream

Is it possible to write to a Node Passthrough stream and then read the data at a later time? I am encountering an issue where my code hangs when trying to do this. Below is a simplified example in Typescript: const stream = new PassThrough(); strea ...

Node.js in action with XmlHttpRequest

I'm having trouble making an XMLHttpRequest call from my client-side JavaScript to my Node server. It seems like nothing is happening and I'm a bit new to this concept. Here's the JavaScript function I've written: function sendTokenToS ...

Unable to instantiate a class using a module in React

I am on a mission to combine Monaco editor and Convergence in order to create a collaborative editor. To achieve this goal, I am referencing the following repositories and examples: https://github.com/convergencelabs/monaco-collab-ext https://github.com/c ...

What is the purpose of the bold line down the left side of every HTML calendar?

Welcome to a calendar layout designed with flexbox: Check it out here Do you notice the thicker lines below the heading rows and want to remove them? Here is how you can modify the HTML & CSS code: #calendars-container { text-align: center; font-f ...

What sets Observables (Rx.js) apart from ES2015 generators?

From what I've gathered, there are various techniques used for solving asynchronous programming workflows: Callbacks (CSP) Promises Newer methods include: Rx.js Observables (or mostjs, bacon.js, xstream etc) ES6 generators Async/Await The trend ...

Ways to emphasize text in a h2 header without affecting other elements

One particular HTML block is causing me some trouble: <h2><span class="numbers">1.1 </span>header text</h2> It's important to note that I did not write this HTML code, so my options for changing it are limited. Howev ...

Steps for creating a CodeBlock in a Next.js Website blog similar to the one in the provided image

Learn how to insert a code block in Next.js. def greet(name): """ This function greets the person passed in as a parameter. """ print("Hello, " + name + ". Good morning!") Here is an example of ...

Transforming a cURL command into an HTTP POST request in Angular 2

I am struggling to convert this cURL command into an angular 2 post request curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -H "Authorization: Basic cGJob2xlOmlJelVNR3o4" -H "Origin: http://localhost:4200/form" -H "Postman-Token: fbf7ed ...

The process of deleting lines from an image using Javascript

If I have an image of a data-table and I want to eliminate all the grid lines (defined as continuous vertical or horizontal pixels), is there a way to achieve this using Javascript's image data manipulation? I envision looping through a 2D array conta ...