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

JavaScript Grouping Arrays

I am working with an array and need to filter it by both Country and Service. So far, I have successfully filtered the array by Country. Now, I want to achieve the same filtering process based on the Service as well. Here is a snippet of the array: [ ...

How can I bind the ID property of a child component from a parent component in Angular 2 using @Input?

I have a unique requirement in my parent component where I need to generate a child component with a distinct ID, and then pass this ID into the child component. The purpose of passing the unique ID is for the child component to use it within its template. ...

Creating a read-only DIV using Angular - a step-by-step guide

Is there a simple way to make all clickable elements inside a div read only? For example, in the provided HTML code, these divs act like buttons and I want to disable them from being clicked. Any tips or shortcuts to achieve this? Thank you. #html < ...

"Select2 dropdown search bar vanishing act: The hunt for results comes up empty

Currently, I am dealing with a scenario involving two modals, each containing a select2 search dropdown. An issue has arisen where selecting modal one filters the dropdown data effectively. However, upon selecting modal two, although the data is filtered i ...

Is it possible to continuously refresh a DIV element?

After spending the past 4 or 5 hours scouring Stack and various other resources, I am still unable to find a solution to my problem. The issue at hand involves an Iframe within a page that displays 5 lines of information fetched from a database. This info ...

Ways to compel links to open in Internet Explorer

In one of my chatbot messages, I have included a link to a web app that is only compatible with Internet Explorer. My chatbot runs on Google Chrome, so when the user clicks on the link, it opens in a new Chrome tab instead of in IE, where it should open f ...

Looking to display the view source of an HTML page, but it keeps redirecting to another site when I try. Anyone know how to diagnose and fix this issue?

Can anyone assist me in displaying the HTML source of a page without it redirecting to another site? Here is the URL: ...

JSONP error: "Syntax error - token not expected"

While attempting to perform a JSONP AJAX request, an error was thrown: Uncaught SyntaxError: Unexpected token I'm puzzled about what is wrong in my code. Can someone assist? $.ajax({ url: 'http://api.server32.trustklik.com/apiv1/website/ ...

Take command of the asynchronous loop

I have two Node.js applications that serve different purposes. The first is an Express.js Server (PROGRAM1), responsible for providing the user interface and RESTful APIs. The second is a web crawler (PROGRAM2), tasked with continuously reading items, do ...

Avoiding the occurrence of moiré patterns when using pixi.js

My goal is to create a zoomable canvas with rectangles arranged in a grid using pixi.js. Despite everything working smoothly, I'm facing heavy moire effects due to the grid. My understanding of pixi.js and webgl is limited, but I suspect that the anti ...

Steps to clear the form in vue after the ajax request has been successfully submitted

Exploring Vue.js Web Form Validation with a Scenario If you are interested in the vue-form validator library, it can be found at https://github.com/fergaldoyle/vue-form For a demonstration of this scenario, check out the following jsfiddle link: https:/ ...

Check for non-null Sequelize Where conditions

Suppose I need to execute a select command using Sequelize with the condition: WHERE ID=2134 However, if the user does not provide an ID, then the WHERE clause should be omitted (as it is null). What is the best way to handle this situation in Sequelize ...

Why is it that a click event outside of an HTML element cannot be detected in this Vue 3 application?

I've been diving into building a Single Page Application using Vue 3, TypeScript, and The Movie Database (TMDB). Currently, I'm focused on developing a search form within my project. Within the file src\components\TopBar.vue, here&apo ...

Using webpack to load the css dependency of a requirejs module

Working with webpack and needing to incorporate libraries designed for requirejs has been smooth sailing so far. However, a bump in the road appeared when one of the libraries introduced a css dependency: define(["css!./stylesheet.css"], function(){ &bsol ...

Strategies for implementing classes in Typescript

I've been working on incorporating more classes into my project, and I recently created an interface and class for a model: export interface IIndexClient { id?: number; name?: string; user_id?: number; location_id?: number; mindbody_id?: nu ...

How can I create two buttons on one line in a Struts2 form?

My form has two buttons - one for registering and the other for canceling the form. I created them using the following code: <s:submit name="cancel" key="project.button.cancel" /> <s:submit name="login" key="form.register.registerBtn" /> How ...

Send an identifier to the following page upon selecting a hyperlink in AngularJS

I am currently working on a project that involves displaying a list of places and allowing users to click on a place to view more details on another page. I would like some guidance on how to implement this feature. Here is the HTML code for Page1: <l ...

Grow an element starting from its center without being limited by the boundaries of a div

I'm faced with a puzzling issue that I believe has a simple solution, but it seems to be eluding me at the moment. Essentially, I have a div containing an image as its background. Upon clicking this div, I want another circular div (created using bord ...

Converting JavaScript code into PHP syntax

I'm curious about code organization. The original code in this snippet is functioning properly: <?php if (isset($_POST['submit'])){ ... ... $invalidField = 2; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD ...

Personalize the layout for vertical table headings and table information

I need help with a table that has vertical headers. I want to remove the extra space within the table header and data cells. Here is the code for my table: <table> <tr> <th class="field">Item ID Number:</th> < ...