Flashing background colors on a website

Can anyone explain why this code won't alternate the background color of my website between two different colors?

<script type="text/javascript">
function blinkit() {
    intrvl = 0;
    for (nTimes = 0; nTimes < 3; nTimes++) {
        intrvl += 1000;
        setTimeout("document.bgColor='#0000FF';", intrvl);
        intrvl += 1000;
        setTimeout("document.bgColor='#FFFFFF';", intrvl);
    }
}
</script>

Answer №1

Give this a try:

function pulseColor() {
    interval = 0;
    window.setInterval(function(){
        interval += 1000;
        setTimeout("document.bgColor='#FF0000';", interval);
        interval += 1000;
        setTimeout("document.bgColor='#FFFFFF';", interval);
    }, interval);
}

Answer №2

Avoid passing strings to the setTimeout function, as it is just as risky as using eval.

Instead, consider implementing a function like this:

function blinkEffect(repetitions, callback) {
    var toggle = repetitions*2, timer = setInterval(function() {
            document.body.style.backgroundColor = toggle%2 ? "#0000FF" : "#FFFFFF";
            toggle--;
            if( !toggle) {
                clearInterval(timer);
                callback && callback();
            }
        },1000);
    return timer;
}
var flashing = blinkEffect(3);
// The background will flash three times.
// You can also stop it with `clearInterval(flashing);`

Using the provided code snippet, you have the option to specify an action to be taken upon completion:

var flashing = blinkEffect(3,function() {alert("Hello!");});

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

Transform gradient backgrounds as the mouse moves

I'm attempting to create a unique gradient effect based on the cursor position. The code below successfully changes the background color of the document body using $(document.body).css('background','rgb('+rgb.join(',')+&a ...

Issue with jQuery week calendar: Existing data not loading correctly into the calendar

I am currently experimenting with the jQuery week calendar plugin found at https://github.com/themouette/jquery-week-calendar/wiki in order to showcase meetings on my website. However, I am encountering an issue where my events.php file is returning JSON d ...

Leveraging createMuiTheme to customize default styles for divs, paragraphs, and the body element

Seeking guidance on customizing a Material UI Theme I aim to modify the default styles for elements like <body>. Currently, at the root of my React tree: import theme from './mui-theme' ReactDOM.render( <Router> <ThemePr ...

I'm curious if there is a contemporary alternative to "Deep Zoom Composer" in Silverlight that enables the creation of panoramic images by stitching multiple images together

There was a time when Silverlight offered a feature known as "deep zoom", which cleverly adjusted bandwidth usage as the user zoomed in and out. Recently, I discovered a unique application for this technology - by incorporating images taken from a hot air ...

Issue with jQuery's outerHeight() function persisting despite attempting to fix it with jQuery(window).load()

Once the content is loaded using AJAX, I need to retrieve the outerHeight of the loaded elements. Ajaxload file: $('#workshop').submit(function(event){ $.ajax({ url: URL, type: 'POST', data: $(' ...

Utilizing jqGrid row identifiers and personalized details using JSON dataset

I'm currently facing an issue with using jqGrid along with JSON data that is returned from the server. Within my grid, I am displaying various types of objects. However, due to the nature of these objects, it is possible for two different objects to ...

Unexpected output from Material UI Textfield

When attempting to print a page of my React app using window.print(), everything prints correctly except for the Textfield component from Material UI. It works fine when there are only a few lines of text, but when there is a lot of text, it appears like t ...

Whenever the page is refreshed, the vertical menu bar with an accordion feature hides the sub

I have designed a vertical accordion menu bar following the example at http://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_accordion_symbol However, I am encountering an issue where clicking on a button to display a submenu causes the page to refr ...

My jQuery DataTables iDisplayLength seems to be malfunctioning. Any tips on resolving this issue?

Currently, I am faced with an issue when trying to retrieve a large amount of data from a MySQL database. To prevent overloading the server, I have set a specific display length for the jQuery Datatable options. However, it seems that despite my efforts to ...

JavaScript post method for JSON data: no input or output values

I am currently developing a page that extracts data from an HTML table consisting of two columns and an index of a form, and then converts it into a JSON string. The intention is to pass this data into PHP for further processing, perform calculations on th ...

Modify the innerHTML to adjust font size when a button is clicked in Ionic 5, or eliminate any unnecessary spaces

I have been experimenting with changing the font size of a variable in .html when the variable contains whitespace. In my .ts page, I use the following code to remove the whitespace: this.contents = this.sanitizer.bypassSecurityTrustHtml(this.product[&apos ...

Arranging Elements Using CSS

Currently, I am working on aligning and positioning my items using CSS. However, I'm a bit confused about the right approach. Here is a demo of my current progress: Demo Link I aim to achieve a layout similar to this sketch: Sketch Image Apologies ...

Retrieving the custom attribute value from the chosen option and storing it in a JavaScript variable

I am currently working on a project that involves a country select input, with custom attributes included in the options. My goal is to retrieve the value of the "name" attribute using JavaScript and then append it to a link for further processing. Howev ...

Adjust the width of content within a wrapper using HTML and CSS to automatically resize

I am facing an issue with a content div that has variable length content arranged horizontally. I want the width of this content div to adjust automatically based on the length of its content. Removing the arbitrary "20%" value from the width property is c ...

Custom Bootstrap 3 Panel Organization

I'm intrigued by the layout shown in the image attached. My attempts to recreate it using a combination of columns and rows have been unsuccessful. Could it be that I'm going about this the wrong way? ...

Styling Angular Datatables with CSS

i have data on the front end https://i.stack.imgur.com/2xq7a.jpg i need all check marks to be displayed in green color. Below is the code snippet: $scope.dtColumnsCal= [ DTColumnBuilder.newColumn('name').withTitle('Name') ...

Can the individual headers of an ag-grid column be accessed in order to apply an on-mouseover event with a specific method?

In my current project, I am utilizing ag-grid to create a dynamic web-application that combines tools from various Excel files into one cohesive platform. One of the Excel features I am currently working on involves displaying a description when hovering ...

What CSS selector should I apply to create a circular profile image for Buddypress users?

In my current WordPress project, I am utilizing the BuddyPress, WooCommerce, and WC Vendors plugins for enhanced functionality. To personalize each vendor's product listings, I decided to display their BuddyPress profile picture alongside their produ ...

Update the content of the document element by assigning it a lengthy string

I'm utilizing JQuery to dynamically assign content to a div element. The content has numerous lines with specific spacing, so this is the approach I am taking: document.getElementById('body').innerHTML = "Front-End Developer: A <br/> ...

Enhance the responsiveness of full-screen pop-ups

My current project involves creating a full-screen pop-up for a specific application. /* Custom Full Screen Popup */ .fullscreen-popup { position: fixed; top: 0; ...