Implementing color transitions in javascript

Everyone talks about transitioning things in CSS, but have you ever thought about transitioning background colors in JavaScript? I'm currently working on a function that changes the background color of a div with the id of ex1 to green. However, I'm facing an issue where the setInterval function is only running once, which is quite strange.

CSS:

<style type="text/css">
div#ex1{color:white; background:black; width:300px; padding:0px 10px 10px; margin-bottom:10px;}
div#ex1:hover{cursor:pointer;}
div#ex1 h2{border-bottom:double 3px white; text-align:center; padding: 5px 0; margin: auto -10px;}
div#ex1 p{text-indent:5px;}
</style>

HTML

<div id="ex1">
  <h2>Transition Color</h2>
  <h4>Text:</h4>
  <p>Church-key seitan listicle locavore, mixtape biodiesel readymade crucifix health goth flexitarian direct trade mlkshk iPhone. Banjo tote bag readymade +1 skateboard deep v. Mixtape cred readymade gentrify. Banh mi keytar butcher, skateboard knausgaard </p>
</div>

Javascript:

document.getElementById('ex1').addEventListener('mouseover', function(e){
 var tar = this;

var counter;

var backG = window.getComputedStyle(tar,null).getPropertyValue('background-color');

console.log(backG);

 var re,gr,bl;
 gr = 0;
 bl = 0;

function chColor(tar)
{      gr =+31;
       bl=+10;
  if ( gr <153 && bl <51)
  { console.log('This is running');
    tar.style.backgroundColor = 'rgb(0,'+gr+','+bl+')';
  } 
  else
  {
    clearInterval(counter);
    console.log(backG);
    console.log('The change has ended');   
  }
}

counter = setInterval(chColor(tar),100);

}, false);

Answer №1

For setInterval to work properly, you need to provide a reference to the function it should call at each interval. In your current setup, you're passing in the result of the function instead. To fix this issue, try the following:

setInterval(function () {
     changeColor(target);
}, 100);

Answer №2

It's important to correct these 2 lines of code by using += instead of =+. Without this correction, the values will never increase.

gr += 31;
bl +=10;

After making those changes, refer to mcgraphix's post for further instructions. You'll need to implement that as well in order to allow the animation to change colors when hovering over text. (I was actually going to mention it myself, but he beat me to it. :)

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 is the best way to align a scalable SVG image in the center?

My goal is to horizontally align this SVG within its container, which could be any div, body, or other element. <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1250 190" preserveAspectRatio="xMidYMid slice" class="svg-content"> &l ...

It seems that an issue has occurred indicating that something is not defined in the current context

Hello everyone, I'm struggling with a problem that I just can't seem to figure out. I've tried multiple solutions but this error keeps popping up and now I'm completely lost. Can someone please help me resolve this issue? The code in q ...

Issue with dynamic creation of menu in React Material UI where onClose function is unable to reference a variable inside the function

As I develop an app, I have chosen to dynamically construct the settings menu based on a JSON file. { categories: [ { name: "General", index: 1, items: [{ name: "Dark Mode", index: 1 ...

javascript guide to dynamically update the glyphicon based on value changes

I am attempting to implement an optimal level feature where a glyphicon arrow-up will be displayed if a value falls within the optimum range, and it will switch to a glyphicon arrow-down if the value is lower. <div class="card-body" ng-repeat="item i ...

Navigate within a single component on the Stack by scrolling

I'm a huge fan of CSS! Although it may seem like a simple task, I am completely stumped on how to tackle it. Mission: My goal is to enable scrolling only within the List section without affecting the entire page. Here's the structure of my ...

How can I clear all jQuery toggled classes that have been added across the entire webpage in an Angular project?

Upon clicking a link within an element, the following CSS is applied: <a class="vehicleinfo avai-vehicle-info-anc-tag" ng-click="vehicleInfo($event)">Vehicle Info <span class="s-icon red-down-arrow"> </span> </a> $scope.vehic ...

Is it possible to retrieve the createdAt timestamp without displaying the 'GMT+0000 (Coordinated Universal Time)'?

After conducting an extensive search, I have yet to find a satisfactory answer. My goal is to configure it without including the CUT time. {name: "Registered:", value: `${user.createdAt}`}, {name: "Joined:", value: `${message.guild.joinedAt}`} Presently, ...

CSS designed for small-screen laptops is also being utilized on iPads running Safari

To specifically target the iPad/Safari browser and accommodate some minor differences in appearance compared to windows/linux browsers, we are implementing the following HTML meta tag and style query: <meta name="viewport" content="width=device-width, ...

SVGs appear at the forefront of all other elements

is where this issue is arising.... specifically in the date selection feature on the left side of the options panel. When using both Google Charts and Material Icons with the date picker component from https://github.com/nickeljew/react-month-picker, we a ...

Removing CSS from an HTML document using Gulp

My Web App is built using Angular and I encountered an issue with Gulp. Every time I add a new custom CSS line to my HTML file and run Gulp, it automatically removes that line from the file. <!--MATERILIZE CORE CSS--> <link h ...

The parser for PHP CSS struggles with interpreting semicolons within property values

I encountered an issue while using a function to parse CSS files. The problem arises when the property values contain semicolons, causing it to break. Here's an example snippet from the CSS file: #logo { background-image: url("data:image/png;base ...

Extra space within table in Firefox

Experiencing an issue with excess whitespace in a table on Firefox. Visit the live example at The problem can also be seen on this jsFiddle: http://jsfiddle.net/DVbCC/ In Chrome and Safari, rows are neatly arranged with minimal spacing, but Firefox show ...

Tips for verifying elements using the Loop technique in a JSON array

I am new to JavaScript and I have been trying to run the following code with an expected result like this: [["00:04:12","05:54:46"],["06:06:42","12:45:22"],["12:51:11","15:56:11"]] However, my script is not working as expected. Can someone please help ...

Guide on showcasing jQuery variable values in PHP on a single page

I have some JavaScript and PHP code that I need help with. I want to assign a jQuery variable value to a PHP variable called $nicks, and then echo the value of $nicks on the same page. <script type="text/javascript"> var axel = 131.5678466; < ...

Can CSS be utilized to define the dimensions and background of a <div>?

Does applying inline styles like <div style="width: ;height: ;background: "> fall under the realm of CSS? ...

Having trouble retrieving Bengali-language data from the server using jQuery AJAX

I am facing an issue where I am unable to fetch data in Bengali language from the server using ajax. Strangely, the data retrieved from the server is getting replaced by some unknown characters. However, if I directly retrieve the data without using ajax, ...

Having difficulty submitting a form with ajax, while accomplishing the same task effortlessly without ajax

I have been experimenting with submitting a form using ajax to the same .php file. When I submit the form without ajax directly (form action), the database gets updated. However, when I try the same process with ajax, there is no change in the database. H ...

Creating a Parent Container to Maintain the Height of the Tallest Offspring

I've been searching online for solutions, but so far I haven't found one that meets all the requirements. <div class="parent"> <div class="child1">I am 60px tall and always visible; my parent is 100px tall</div> <div ...

Leveraging NextJS to perform server side rendering by injecting parameters from a caller component

I'm currently in the process of creating an application with a storefront using nextJS. I've successfully utilized getServerSideProps when loading a new page. This particular page is quite complex, as it consists of multiple components, each req ...

Using JavaScript to develop a demonstration of the capabilities of Microsoft's Cognitive

Having trouble getting this basic example of the Microsoft Cognitive Services to work in JavaScript. Need some help or a working example, please! I've attempted to run the code in both node and browser with necessary modifications. Encountering an e ...