Make the JavaScript text blink for an extended period of time in a single color

I am facing an issue where I want to make text flash between yellow and grey colors, but I want the yellow color to display for a longer duration than the grey color.

Currently, the code I have only works for an equal duration for each color.

function flashtext(element, color) {
    var tmpColCheck = document.getElementById(element).style.color;

    if (tmpColCheck === 'grey') {
        document.getElementById(element).style.color = color;
    } else {
        document.getElementById(element).style.color = 'grey';
    }
}

setInterval(function() {
    flashtext('flashingtext', 'yellow');
}, 700); // set an interval timer to repeat the function

Does anyone have any suggestions to improve this code?

Answer №1

Is this what you had in mind?

function changeColor(id, color) {
    var isGrey = true,
        element = document.getElementById(id);
    (function loop() {
        isGrey = !isGrey;
        element.style.color = isGrey ? 'grey' : color;
        setTimeout(loop, isGrey ? 500 : 1000);
    })();
};

Check out the demo at http://jsfiddle.net/alnitak/8LYG2/

In this code snippet, the variable isGrey is used to keep track of the current state instead of directly reading it from the element. This approach is efficient and removes the chance of the browser converting the .style.color property. The inner function is responsible for toggling the state, updating the element's style, and setting the next loop with the correct timeout.

Answer №2

If you want to add flashing text on your website, you can achieve it by using the setTimeout function in JavaScript. Here is a simple example:

function flashtext(ele, col) {
    var tmpColCheck = document.getElementById(ele).style.color,
        time;
    if (tmpColCheck === 'grey') {
        document.getElementById(ele).style.color = col;
        time = 1400;
    } else {
        document.getElementById(ele).style.color = 'grey';
        time = 700;
    }
    setTimeout(function() { flashtext('flashingtext', 'yellow') }, time);
}
flashtext('flashingtext', 'yellow');

If you want to see a demo of this in action, check out this DEMO: http://jsfiddle.net/EfpEP/

Enhanced Version:

Here is an improved version of the function that optimizes the code:

function flashtext(ele, col) {
    var style = document.getElementById(ele).style;
    (function main() {
        var cond = style.color === 'grey';
        style.color = cond ? col : 'grey';
        setTimeout(main, cond ? 1400 : 700);
    })();
}
flashtext('flashingtext', 'yellow');

For a better demonstration of this enhanced version, visit this DEMO: http://jsfiddle.net/EfpEP/3/

It's important to note that storing the color value can prevent potential browser inconsistencies. To further improve the function, consider the following approach:

function flashtext(ele, col) {
    var style = document.getElementById(ele).style,
        cond = style.color === 'grey';
    (function main() {
        cond = !cond;
        style.color = cond ? col : 'grey';
        setTimeout(main, cond ? 1400 : 700);
    })();
}
flashtext('flashingtext', 'yellow');

Explore the updated version with this DEMO: http://jsfiddle.net/EfpEP/4/

Further Optimization:

If you plan to apply flashing text to multiple elements simultaneously, consider using the following approach to prevent browser freezing:

// Code snippet for optimized flashing text functionality

To see this in action, check out the DEMO: http://jsfiddle.net/EfpEP/6/

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

What causes the discrepancy between the nodejs package on GitHub and the version downloaded through npm?

After committing to installing a nodejs package with npm install -g package_name, I noticed that some of the downloaded packages have different files compared to the same package on Github. Why is this discrepancy present? ...

Preventing Background Scrolling While Modal is Open in React - Using 'position: fixed' causes the page to unexpectedly scroll back to the top

Currently working on a React website where users can scroll through various posts on the homepage. Each post includes a '...' menu that, when clicked, opens up a modal with additional options. In order to prevent the background from scrolling w ...

Easily generate a component directory complete with all essential files in just a few simple clicks

In my work with React and the typical app structure, I utilize a directory called src/components to store all of my React components. I am looking for a way to streamline the process of creating new components. I would like to be able to generate a compon ...

"Converting circular structure into JSON" - Inserting BigQuery Data using Cloud Function in Node.js

I am currently facing an issue while attempting to load an array of JSON objects into a BigQuery Table from a Cloud Function built in NodeJS. Despite not having any circular references, I encountered the error message "Converting circular structure to JSON ...

Checking for duplicate entries in an array created with the Angular form builder

I am currently utilizing angular6 reactive form with form builder and form array. The issue I am encountering is duplicate subject entries from the drop down in the form array. How can I implement validation to prevent duplicate entries in the form array? ...

Only the initial element within the specified class is targeted by JQuery

Currently, I am utilizing Kendo UI to refresh multiple charts by class without having to access each one individually. Here is the code snippet I am using: $(".k-chart").data("kendoChart").refresh(); The issue I am encountering is that only the first cha ...

Having trouble retrieving a customized header from the HTTP response

I've encountered an issue with my Node.js server where I set a custom header. I added the Access-Control-Expose-Headers to allow access from browsers, and it works fine in Chrome and Firefox. However, I'm getting an error in PhantomJS saying "Ref ...

Babel fails to substitute arrow functions

After setting up babel cli and configuring a .babelrc file with presets to es2015, I also installed the es2015 preset. However, when running the command babel script.js --out-file script-compiled.js, I noticed that arrow function syntax (=>) was still p ...

jQuery DataTable error: Attempted to set property 'destroy' on an undefined object

<script> $('#archiveTable').DataTable({}); </script> <table id="archiveTable" datatable="ng" class="table table-sm" style="color:black"> <!--some code--> </table> This is a snippet of HTML code Upon checking t ...

Comparison between SSD and HDD animation speed in web hosting environments

I am currently in search of a web hosting provider for a website I have created. The site features some performance-heavy animations, particularly due to a fullscreen slider with filter and scaling transitions. I need a provider that can ensure optimal per ...

JavaScript: Scroll Through Images Horizontally with Descriptions for Each Image

I am looking to create a horizontal scroller/slider that will display images with captions underneath each image. The data is provided in an array of objects, so I need to iterate through the data and populate each item in the scroller with the necessary i ...

Troubleshooting a Tiny Bottom Sheet Problem in react-native

On my page, I have a bottom sheet that takes up 3/4 of the space. Then, within that bottom sheet, I open another bottom sheet that only occupies 1/4 of the space (without closing the first one). ...

Enhancing jQuery Functionality with Parameter Overrides

While it may seem like a simple question, I am new to writing jQuery plugins and could use some clarity on scope rules in JavaScript. My goal is to create a jQuery plugin that interacts with the Stack Overflow API. I have started exploring the Flair API f ...

React does not allow objects as a valid child element. This error occurs when an object with keys {nodeType, data, content} is found

I am encountering an issue with displaying content from Contentful on the server component. Everything is functioning correctly with no runtime errors, but I am receiving this specific error message: "Objects are not valid as a React child (found: object w ...

Glitch in JavaScript: Converting Text to Numbers

My current challenge involves converting text into numbers using code. Here is the code snippet I have: var vals= ["a","b","c","d","e","f","g","h","i","j", ...

When sending a POST request, the req.body.someElement parameter is not defined

Encountering an issue with a post request, as req.body is returning undefined values. Despite researching on Google and Stack Overflow, the provided solutions have not resolved the problem. Although logging the name shows a value, trying to access req.body ...

Is there a way to use jQuery to automatically make a field stand out visually?

I am looking for a way to make a text field automatically underline as the user types. The line should follow along with the characters in real-time, and when the user moves away from the field, I want the line to fill up the entire width. This signifies t ...

Javascript - Error encountered when utilizing a for loop to insert a new column into an array

I have been utilizing an API to fetch data on various stocks, and I am attempting to include a column named "symbol" with the query values using the function insertColumn. However, I am encountering an error message that says (node:15732) UnhandledPromiseR ...

What is the best way to show a macOS progress pie loading icon alongside files?

While using macOS, a pie loading icon appears next to a file during downloading or transferring. To illustrate, here is an example of a file being downloaded from Chrome: https://i.sstatic.net/8jS4X.png I am interested in implementing a similar feature i ...

Creating a precise regular expression for route length in Express JS

Currently, I am facing an issue while setting a route in my application. I want the URL parameter to be exactly 2 characters long, but unfortunately, the following code snippet is not producing the desired result: app.all('/:lng{2}?',function (r ...