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

The dropdown in vue-multiselect automatically closes after the first selection is made, ensuring a smooth user experience. However,

I am experiencing an issue where the dropdown closes after the first selection, despite setting close-on-select="false". However, it works properly after the initial select. You can observe this behavior directly on the homepage at the following link: vue ...

Utilizing EventEmitters for cascading operations in Angular 2 dropdown menus

I have a form with several cascading drop-downs - the selection in one drop-down determines the options available in the next. Each drop-down retrieves its values from an async data service, and Angular EventEmitter is used to handle events and populate su ...

Utilize ramda.js to pair an identifier key with values from a nested array of objects

I am currently working on a task that involves manipulating an array of nested objects and arrays to calculate a total score for each identifier and store it in a new object. The JSON data I have is structured as follows: { "AllData" : [ { "c ...

VUE 3 inexplicably failing to display the custom component's template, console remains error-free

I am utilizing flask, html, js for building a web application. I am currently facing an issue where the template defined in the component <add-movie> within movies.js is not being rendered into add_movies.html. The add_movies.html extends base_admin ...

When the Image Icon is clicked, the icon itself should become clickable and trigger the opening of a popup Dialogue Box for uploading a new image

When I click on the image icon, it should be clickable and a popup dialogue box will open to upload a new image. Check out this sample image for reference. Any help on this would be greatly appreciated. Thanks in advance. <div class="d-flex align-ite ...

Styling Drawn Elements on a Canvas Using CSS

Can CSS Animations be applied to a circle drawn on a canvas using JavaScript? Specifically, I am using an AngularJS directive for this purpose: https://github.com/angular-directives/angular-round-progress-directive/blob/master/angular-round-progress-direct ...

Store the output of JavaScript in a PHP variable

My objective is to convert any image to base 64 and then store the converted string in a PHP variable before inserting it into my database. JavaScript Code: function uploadFile() { if (this.files && this.files[0]) { var FR= new FileReader ...

Looking for assistance in merging CSS and HTML codes?

I am working on combining two different codes and could use some assistance. Here is the HTML code: <div class="loader"> <span></span> <span></span> <span></span> </div> Followed by the CSS cod ...

Step-by-step guide on implementing virtual scroll feature with ngFor Directive in Ionic 2

I am working on a project where I need to repeat a card multiple times using ngFor. Since the number of cards will vary each time the page loads, I want to use virtual scrolling to handle any potential overflow. However, I have been struggling to get it ...

Managing the display of numerous ngFor components

If you're interested in learning more about the features I will include, here's a brief overview. I plan to have a project section with cards displayed for each project, all populated from a JSON file. When users click on a card on the website, a ...

What is the process for activating the quasar timepicker once a user has selected a time?

The functionality of the timepicker in Quasar doesn't quite meet my expectations. I don't want to add another library just for this feature. The main issue I have is that it doesn't close automatically after selecting a time. I managed to fi ...

(angular 8) Error occurred when converting a file or image to FormData due to an invalid value (Note: FormData object printed as Object Form{})

I encountered an issue where I am getting an invalid value from form data. The value appears correct in `this.fileData` with a size of 5701, but becomes empty when converted to form data - `{}` is logged when I console.log the form data. Additionally, acce ...

Determine whether an element has the capability to hold text content

Is there a surefire and reliable method to determine if an HTML element is capable of holding text, using only pure JavaScript or jQuery? For example, <br>, <hr>, or <tr> cannot contain text nodes, whereas <div>, <td>, or < ...

Nodejs - Utilizing Express and Mongoose to Implement URL Routing by Name

My Express 4 server has CRUD routes specifically for authors: router.get('/authors', AuthorsController.index); router.post('/authors', AuthorsController.store); router.get('/authors/:name', AuthorsController.show) ...

Tips for monitoring password and password confirmation fields in DevTools when using AngularJS forms

Within the ng-model, I have identified two variables: vm.user.password and vm.confirmpassword. The input fields are equipped with attributes such as id, name, and class. I am interested in monitoring both the password and confirmpassword values within Dev ...

Encountering continuous errors during NPM installation

As a newcomer to React, I'm facing challenges in building components and getting my page up and running while following a tutorial. When attempting to npm install dropzone, I encounter a barrage of error messages and an empty tree when checking npm li ...

Is it possible to modify the class attribute of an HTML element in PHP upon clicking an input?

In this assignment, I am restricted to using only PHP and cannot incorporate JavaScript. Currently, my code is set up to detect a post from an input type="submit" and then check for empty or filled text inputs. The code currently echoes text based on the c ...

Tips on extracting variables from JMeter Selenium WebDriver

Currently, I am dealing with a token that is being returned in the body of a web page. WDS.browser.findElement(org.openqa.selenium.By.xpath("//*[contains(@name,'RequestVerificationToken')]")).getText(); This token is what I need to extract: ...

Having trouble getting a local npm installation to work from a specific file path?

After following the instructions from this helpful link to install an npm package through a file path, I encountered an error when attempting to use it: Cannot find module '<module_name>' or its corresponding type declaration Are there an ...

Need Root Directories in Browserify and Using NPM (eliminating the constant use of '../../../..' in both cases)

Despite my extensive search for a solution to this issue, I have been unsuccessful so far – even after referring to the amazing gist on improving local require paths and thoroughly reading the Browserify handbook section on Avoiding ../../../../... I am ...