Alternate the color over time using CSS

Is there a way to dynamically change the color of a div from black to white every two seconds, and then from white to black, continuously toggling as long as the div is visible? Essentially, I want the div to only be displayed when a user clicks and drags on a surface (similar to the desktop selection area), and my goal is to alter the border color in the described pattern while the user is actively making their selection on the surface, as if resizing the div.

Answer №1

If you have browser capabilities that support CSS3, there is no need for any JavaScript at all.

HTML:

<div class="blinkdiv">
</div>

CSS:

@-webkit-keyframes blackWhite {  
  0% { background-color: white; }
  50% { background-color: white; }
  51% { background-color: black; }
  100% { background-color: black; }
}

.blinkdiv {
    height: 100px;
    background-color: black;
    -webkit-animation-name: blackWhite;  
    -webkit-animation-iteration-count: infinite;  
    -webkit-animation-duration: 2s; 
}   

Check out this example: http://jsfiddle.net/tommcquarrie/w3Qy9/1/

Answer №2

This code snippet creates an animation that transitions the background color from black to white every 2 seconds and repeats indefinitely.

body {
    -webkit-animation: colorTransition 2s infinite;
}

@-webkit-keyframes colorTransition {
    0% {background-color: black;}
    100% {background-color: white;}
}

Check out the jsFiddle demo.. Please note that this code has only been tested in Chrome.

Answer №3

To achieve this effect, you have a couple of options. One way is to use a setTimeout function that continuously triggers another setTimeout until the div is no longer visible. Another approach is to utilize a setInterval function to switch the color back and forth, with the ability to stop the transition using clearInterval when needed. Personally, I find the latter method to be more direct, so I will proceed with that:

var toggleIntervalId = setInterval( function() {
    var $div = $('#toggleMe');
    if( $div.length ) {
        $div.attr( 'background-color', $div.attr('background-color')=='black' 
            ? 'white' : 'black' );
    } else {
        clearInterval( toggleIntervalId );
}, 2000 );

Answer №4

If you're considering your needs and utilization of CSS3 (or lack thereof), you might want to achieve this using Javascript/jQuery. jQuery, in particular, could be beneficial, and exploring jQueryUI could be a good idea.

For more information, you can refer to this query on StackOverflow.

For quick results, here's a versatile Fiddle adapted from the aforementioned question which might meet your requirements or at least act as a starting point. However, I recommend further research and exploring the provided links.

The Fiddle's code:

JQuery:

function changeColor(element, curNumber){
    curNumber++;

    if(curNumber > 2){
        curNumber = 1;
    }
    console.log(curNumber);
    element.addClass('color' + curNumber, 500);
    element.attr('class', 'color' + curNumber);
    setTimeout(function(){changeColor(element, curNumber)}, 1000);  
}

changeColor($('#testElement'), 0);

CSS:

.color1{
    background: white;
    color: black;
}

.color2{
    background: black;
    color: white;
}

HTML:

<div id="testElement">This will change colors</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

Struggling to properly implement the prepend logger feature in the code

A function I have created is capable of adding a specified string to the start of each line, whether using streams or a console.log()-like method. Below is the code for this function: // This function prepends a string to each line in a stream exports.lp ...

Adjusting the dimensions of the "overflow avatar" to be consistent with the other avatars displayed in AvatarGroup

When setting the max prop of the AvatarGroup, the additional avatar does not match the height of the other avatars. <AvatarGroup max={3}> <Avatar alt="Remy Sharp" src="/static/images/avatar/1.jpg" sx={{ width: 24, height: 24 ...

Chic and perfectly aligned stripe button design

I need assistance with centering and styling the Stripe checkout button labeled "update card." Additionally, I want to adjust the appearance of the card number input field to be normal but readonly. How can I achieve this without relying on Bootstrap' ...

Troubleshooting Display Problems when Switching Bootstrap Themes in ASP.NET MVC

I recently made changes to my MVC project by switching the default Bootstrap theme to Bootswatch - Cosmos. However, I am facing an issue with the Navbar as shown in the image below: View Header Display Issue Image Initially, I was using Bootstrap 3.0 and ...

Connect an Angular Service object to a Controller's Scope and keeping it in sync

I am facing an issue with the interaction between my EmployeeService and EmployeeController. The service contains a specific object which I bind to the controller's scope: app.controller('EmployeeController', function($scope, EmployeeServic ...

How to Retrieve the Name of the Active Element from an Unordered List (<ul>) in ReactJS and Display it in the

I have a project where I am creating a long navbar specifically for mobile devices, and I am structuring it in an accordion style. Initially, the view will show the currently active link name. When the user clicks on this active link name, it expands below ...

How can I remove the back button that the Ionic framework adds when using $state.go('app.home') to navigate to a page?

I have an app with a sidebar menu. Currently, I am on the second page and I am calling a controller function that redirects me to the first page using: $state.go('app.home'); The issue I am facing is that on this page, a back button is displayed ...

Can you show me how to line up a series of table rows and use jQuery to slide them up or down?

Imagine a scenario where there is a table with 50 rows, each containing parent/child relationships. The goal is to click on a parent row and expand/collapse all its children rows simultaneously by sliding them up together. How can this be achieved? Consid ...

Transfer information from the ajax success event to an external else/if statement

I am encountering an issue when trying to transfer the appropriate result from my ajax success function to an external function for further use. Currently, I am using user input to query a data source via ajax and receiving the object successfully. The re ...

Is there a way to change the format of a date and time from YYYY-MM-DD hh mm ss to MonthName, date, year | Hour:Minutes (am/pm) using

How can I convert the date string (2013-03-10 19:43:55) into the format (Mar 10, 2013 | 7:43 pm) using JavaScript or jQuery? ...

Tips for adjusting the width of columns automatically in exceljs

One of my challenges is to automatically adjust column width using exceljs. I want the Excel sheet to be dynamic, saving only the columns specified by the user in the request. Here is the code snippet that accomplishes this: workSheet.getRow(1).values = dt ...

Keycloak does not support using the updateToken() function within an asynchronous function

In our development of a Spring application with React/Redux frontend, we faced an issue with Keycloak authentication service. The problem arose when the access token expired and caused unexpected behavior in our restMiddleware setup. Here is a simplified v ...

Dollar Sign vs "$$()" Sparkling Protractor with "by.css()" vs "$()"

I'm a bit confused about the purposes of the $ and $$ commands. I initially thought they were just substitutes for 'by.css', but why use $$? <element id = "eId"></element> Based on the example above, I assumed that these two l ...

res.send No data being transmitted - in the realm of Express.js

I'm currently developing a calculator app using Express.js, but I seem to be encountering an issue with the res.send Method as I am not getting any response. My expectation is for my webpage to display the sum from the calculator.js file. Nodemon is a ...

Harnessing the power of JSON within an HTML document to display dynamic data

Check out the JSON data through this link: The JSON file contains information about the weather. I need assistance with incorporating the data from the provided link into my HTML document as I am new to utilizing JSON for this purpose. <html> < ...

Can AngularJS support HTML5-mode URL routing in locally stored files (using the file:// protocol)?

Sorry if this question has already been asked, but I haven't been able to find any information on it. I'm working on an AngularJS application that needs to be accessed directly from a hard drive (not through a traditional HTTP server), so the UR ...

I am able to successfully receive accurate data in JSON format, however I am facing difficulties binding it to a jquery

I am struggling with integrating data fetched in JSON format using $.ajax into a table using jquery's datatable. Below is the JavaScript code I have been trying: $(document).ready(function () { $.ajax({ type: "POST", url: "Result.aspx/getUser ...

The dragging and dropping feature for HTML input type="file" is not functioning properly in Edge and IE11

I've developed an Angular app using this sample where I have included only an input control on the screen. Within my project, I constructed a custom file-uploader component. While I am able to drag and drop files in Chrome, I encountered issues with d ...

Top method for efficiently inserting multiple rows into a database from an HTML table using AJAX

I need to store data from HTML table rows in a database. Each row contains 20 values, and there are about 200 rows that need to be inserted. I have two possible solutions: A. I can send the data for each row (20 values) through AJAX, repeating this proces ...

Discovering the special HTML element lacking attributes

When two similar tags, such as anchor tags below, do not have any attributes or css properties associated between them, is there an internal property to distinguish between the two? <html> <body> <a>sample</a> <a>s ...