Streamlined method for handling child elements within the DOM

I am striving to achieve a randomized shine effect on specific text using CSS animation. I currently have a functioning code, but I am interested in learning if there is a more efficient or straightforward solution.

HTML:

<span class="foo">
    <span class="bar">
    </span>
</span>

CSS:

@keyframes masked-animation {
    0% {background-position: -1000px 0}
    50% {background-position: 1000px 0}
    100% {background-position: 1000px 0}
}

.foo{
    text-align: center;
    font-size: 40px;
    font-weight: bold;
    display: block;
    color: red;
    position: absolute;
}

.bar{
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    color: rgba(0,0,0,0);
    background-image: linear-gradient(-45deg, rgba(255,255,255,0) 0%, rgba(255,255,255,0.67) 48%, rgba(255,255,255,     
   0.9) 50%, rgba(255,255,255,0.67) 52%, rgba(255,255,255,0) 100%);
    background-repeat: no-repeat;
    -webkit-background-clip: text;
    animation-name: masked-animation;
    animation-timing-function: ease-in-out;
    animation-iteration-count: infinite;
    background-size: 400% 100%;
 }

JS:

$('.foo')[0].childNodes[0].nodeValue = "Text";
$('.foo > .bar').css({
    "animation-duration" : 8 + Math.round(Math.random()*40)/10 + "s",
    "animation-delay" : Math.round(Math.random()*100)/10 + "s"
}).text("Text");

To ensure the animation displays correctly, it must be placed above the element/text. Placing it on the same element will cause it to appear behind. I attempted to use ::before, but I encountered difficulty selecting it with JS as it doesn't physically exist in the DOM.

This effect needs to be implemented on multiple elements, and the text inside <span> changes periodically.

JSFiddle

Answer №1

If you're looking for an alternative approach, one option is to dynamically create and manipulate a style sheet using JavaScript. By doing this, the task of iterating over elements is offloaded to the browser rather than being handled solely in JavaScript.

MDN provides examples on how to set up such a stylesheet through CSSStyleSheet.insertRule().

For those who prefer working with jQuery, there's a useful jQuery library available for these types of manipulations.

You can also check out a live example here:

var styleElement = document.createElement('style');
document.head.appendChild(styleElement);

var styleSheet = styleElement.sheet,
    ruleIdx = styleSheet.insertRule('.target{}',styleSheet.cssRules.length),
    rule = styleSheet.cssRules[ruleIdx],
    colorize = function() {
        var color = Math.random() * 360;
        rule.style.color = 'hsl('+color+',100%,50%)';
    },
    interval = setInterval(colorize,1000);
colorize();
<div class="target" style="font-size:5em;font-weight:bold;font-family:sans-serif">TEST</div>

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

Manipulate a table using Jquery's find() method to insert a cell populated with information from an array using before()

My current challenge involves inserting a column of cells with data from an array. Despite attempting to use a for loop, all the cells end up displaying the same data from the array. What I really want is for each new cell to show 'row_header1', ...

Sharing information between controllers while being initiated using $rootScope.$emit

I've created a common module that includes a controller, component, and template to initialize the app and set up the base layout. Within this module, there is also a stateful component that makes an HTTP GET request during initialization to fetch a b ...

Looping through Angular promises sequentially

I am faced with a dataset consisting of the following information. $scope.orders = [ { material: 'A', quantity: 32, orderNumber: 'dummy'}, { material: 'A', quantity: 65, orderNumber: 'dummy'}, ...

Ways to set the minimum width of a div depending on its contents

As I work on my website, I encountered an issue with a div containing a table. The div expands to full width, but when I resize the screen, it shrinks causing the content to overlap. I am looking for a solution where the minimum width of the div adjusts b ...

Issue encountered while serializing the `.product` object retrieved from the `getStaticProps` function in NextJS, in conjunction with

I ran into an error message saying "Error: Error serializing .product returned from getStaticProps in "/products/[id]". Reason: undefined cannot be serialized as JSON. Please use null or omit this value." This issue occurred while I was attempting to crea ...

React Native encounters issues with removing the reference to the callback attribute upon unmounting

Utilizing a component that I place in an array (of various sizes) and controlling individual components through refs, while adding refs to an object to keep track of each separately. constructor(props){ super(props); this.stamps = []; this.get ...

Utilizing JavaScript's Array.sort() method for sorting objects with varying properties

Currently, I am dealing with these specific Objects: let obj1 = { from: Date, to: Date } let obj2 = { date: Date } These Objects have been placed in an Array: let arr = [ obj1, obj2 ] My goal is to organize the objects within the array by using arr.sort( ...

Generate a Calendar Table using JavaScript in the Document Object Model (DOM

I have set up a table with 6 rows and 5 columns. The purpose of the table is to represent each month, which may have varying numbers of days. I want each column to display dates ranging from 1-30 or 1-31, depending on the specific month. Here's what ...

Is it better to use regexp.test or string.replace first in my code?

When looking to replace certain parts of a string, is it better to use the replace method directly or first check if there is a match and then perform the replacement? var r1 = /"\+((:?[\w\.]+)(:?(:?\()(:?.*?)(:?\))|$){0,1})\ ...

Is there a way to manipulate the placement of an image within a div using CSS?

Teaching myself HTML has been quite the journey. Right now, I'm in the process of building a website purely for its aesthetic appeal, and I seem to be hitting a roadblock with the CSS/div element. As of now, it appears like this. When the h1 is remove ...

I'm encountering an issue with the "z-index: -1" property in React

After creating a form placed alongside buttons, I encountered an issue where the form overlaps the buttons and prevents them from being clicked. Despite setting the z-index to -1, it seems that the form remains clickable even when not visible. Research ind ...

Delete JavaScript functions and events from memory once the JavaScript code has been removed from the HTML file

I am encountering a situation with my website where popups loaded via ajax also load JavaScript code, which I want to remove when the popup is closed. The main site code looks like this: <body> ... <div id="popup" style="display:none"> < ...

Utilizing JavaScript to Extract JSON Information from Knockout.js

Incorporating knockout into my project has been a great help as I retrieve JSON objects using Ajax. One question that arises is how to effectively utilize this data in my custom JavaScript code: After receiving the mapped item from the ajax call, here is ...

The image slide change feature ceases to function properly when incorporating two separate functions

I have a function that successfully changes the image of a container every 5 seconds. However, I am facing an issue when trying to add 2 containers side by side and change their images simultaneously. When I run the functions for both containers, only one ...

Transitioning smoothly from mobile to tablet views with the sidebar activated in Semantic-UI

My HTML includes a pointing menu when the screen width exceeds 630px. Below 630px, it switches to a sidebar with a menu button: <nav class="ui inverted sidebar menu vertical slide out" id="m_menu"> <a href="index.php" ...

What are the steps to installing and utilizing the Chart.js package on your local machine?

I thought installing chart.js on my Raspberry Pi would be a simple task, but I seem to be struggling with it. Due to the nature of my project, I need to have it installed locally rather than relying on an online version. Following the usual steps, I navig ...

Describe the CSS that targets pseudo-elements on an individual element

Perhaps a Repetition: CSS Pseudo-classes with inline styles Could an example like this work... <span style="this:hover{color:blue}">Changes color to blue when hovered</span> ...be doable? ...

Managing the React Router component as a variable

I'm currently working on integrating React-Router into an existing React app. Is there a way to use react-router to dynamically display components based on certain conditions? var displayComponent; if(this.state.displayEventComponent){ {/* ...

Incorporate JSON into the selection choices

After working with PHP for a while, I decided to start learning how to work with JSON. I managed to successfully create a PHP file that returns JSON data. In my main file, I referenced the PHP file and was able to retrieve the JSON objects. One of the thi ...

Guide on converting data from PHP to JSON using JavaScript

Here is some data that I need to loop through: image1 url1 description1 image2 url2 description2 image3 url3 description3 image4 url4 description4 image5 url5 description5 After looping through the data: var imagesDataArray = [ { src: &apo ...