The div is unable to keep up with the quickly changing colors

I am facing an issue with the color changing too frequently on mouse move. I want it to be delayed and smooth, but the current code is not working as expected.

I tried adding delay(), but it doesn't seem to be effective.

I need help understanding what I'm missing in grasping the concept of using delay in this code.

Below is the jQuery Code-


var possible = 'ABCDEF123456';
var stringLength = 6;
$('#divcol').on('mousemove',function(){
    var randomString = Array.apply(null, new Array(stringLength)).map(function () {
        return possible[Math.floor(Math.random() * possible.length)];
    }).join('');
    
    var col = "#" + randomString;
    $(this).delay(10000).css("background-color", col);
})

The HTML -

<div id="divcol" style="width:150px;height:150px;background-color:#c3c3c3;">
</div>

Here's a link to the Fiddle to see the code in action - http://jsfiddle.net/83mN7/

I am aiming for something similar to this -

Answer №1

Implementing the jQuery animation is key in making this happen:

$(this).animate({ backgroundColor: colorVar }, 1000);

Answer №2

While not the most elegant solution, this code snippet gets the job done:

http://jsfiddle.net/83mN7/20/

var choices = 'ABCDEF123456';
var length = 6;
var counter = 0;
$('#divcol').on('mousemove', function () {
    var randomString = Array.apply(null, new Array(length)).map(function () {
        return choices[Math.floor(Math.random() * choices.length)];
    }).join('');
    var color = "#" + randomString;
    counter++;
    if (counter > 30) {
        $(this).css("background-color", color);
        counter = 0;
    }

});

Answer №3

Have you explored using css3 transitions for this task? You may want to take a look at these helpful css tricks. Keep in mind that using css3 transitions might necessitate a jQuery fallback for older browsers like Internet Explorer 9 that do not support these effects, but a tool like Modernizr can assist with that:

if (!Modernizr.csstransitions) {
    $(".test").hover(function () {
        $(this).stop().animate({ backgroundColor: "#ff0000" }, 1500)
    }, function() {
        $(this).stop().animate({ backgroundColor: "#0000ff" }, 1500)
    });
}

An added benefit of utilizing css3 transitions is that they are browser-native, which means that the animations can be GPU-accelerated, resulting in smoother animation effects.

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

In the three.js scene, a lone particle stands out, capturing all attention

I am currently working on a project to generate a sphere with particles scattered randomly across its surface. The idea is for these particles to move based on the position of the mouse cursor, creating an effect similar to the image linked here: https://i ...

What is the process for transforming a string into a Cairo felt (field element)?

In order to work with Cairo, all data must be represented as a felt. Learn more here Is there a way to convert a string into a felt using JavaScript? ...

Utilizing ng-repeat to loop through a div element that consists of various nested tags

I need to display multiple tabs, with each tab having a table where the values are populated from a database. The number of tabs is dynamic and fetched from another page of the application. All tables have the same structure but different values. How can I ...

Unable to combine theme color with text or background

After customizing Bootstrap's theme colors in my SCSS file, I encountered an issue. Here is how I did it: // set variables $primary: #8dc3a7; $light: #b4d6c1; $starorange: #df711b; // import functions and variables @import "../node_modules/boots ...

Inform the Rails controller about the view that triggered the action

Two different views are invoking the same controller create action, allowing users to "Track" a product. When the user clicks the "Track" button, an AJAX request is submitted using the remote: true attribute. The JavaScript response should re-render the sp ...

Guide to deactivating the selected value in a dropdown list (vue.js 2)

Here is an example of my component structure : <div id="demo"> <div> <select class="form-control" v-model="selected" required> <option v-for="option in options" v-bind:value="option.id">{{ option.name }}</option> ...

An issue arose in Leaflet where drawing on the map became impossible after making an update to a marker's position

I have been working with Leaflet, Leaflet-draw, and Cordova Geolocation. Initially, when the map is loaded in globe view, drawing works perfectly. However, when the locate function is called to update the map center and marker position, drawing becomes imp ...

The issue with React Suspense not functioning properly has left me perplexed and I am struggling to identify the

I have been given a task to investigate why the code below is not functioning properly. This code is an attempt to utilize the React Suspense API, but it is not implemented correctly. There are 3 main issues with how these components are using Suspense ...

Tips for utilizing the vuetify readonly prop while enabling the selection menu

In my project, I have a grid containing v-autocomplete components with the multiple attribute. To maintain clean formatting, I decided to show only a shortened version of the content using the selection slot feature provided below: <v-autocomp ...

Ensure that users must confirm their actions through a message prompt when attempting to exit the website

Looking to add a confirmation box that pops up when someone tries to leave my website. It's important to prevent any information from being lost if they accidentally navigate away. Can you provide detailed instructions on where exactly I should place ...

Combining the keys of two objects in JSON

console.log(a) ; // output in console window= 1 console.log(b);// output in console window= 2 var c = {a : b};// Is there a better way to do this? var d = JSON.stringify(c); d = encodeURIComponent(d); I want the final value of d to be {1:2}. ...

Stacking background images in CSS above other contained elements in a div

I've been experimenting with adjusting the z-index of elements in my code but haven't had any luck. Is it even possible to achieve what I want? Within a div element, I have set a background image using CSS. Inside this div, there are other eleme ...

"Rearrange elements on a webpage using CSS and HTML to position one

Can we utilize CSS/HTML to visually move a full width element that is positioned below another one so that it appears above without altering the markup order? <div id="first">first</div> <div id="second">second</div> #first {…} ...

How to retrieve values from multiple checkboxes in Angular?

After retrieving data from getListOfCurrentSubtenants and displaying it as shown in the screenshot, users have the ability to select items by clicking on checkboxes. How can we capture all the selected data into a single object? For example, if a user che ...

Struggling to locate a counterpart for ruby-toolbox specifically designed for javascript libraries

I've been on the hunt for a website like ruby-toolbox.com, but my search has come up short. Can anyone suggest a reliable and current registry of JavaScript libraries that is well maintained? ...

Angular Appreciation Meter

Looking to create a rating system using Angular. The square should turn green if there are more likes than dislikes, and red vice versa (check out the stackblitz link for reference). Check it out here: View demo I've tried debugging my code with con ...

Troubleshooting a Recursive Menu Problem in Vue.js

I've been attempting to create a recursive menu in Vue.js, but I keep encountering an error and I'm struggling to identify the issue. Here is my current structure: MenuList.vue <template> <ul class="menu"> <MenuLink v ...

Only conceal the breadcrumb trail on the 404 error page

I have recently created a custom node for my site's 404 page with the path /node/83 in the site information. However, I am facing an issue where I cannot hide the .breadcrumb element using display:none. I attempted to achieve this through CSS injector ...

Error encountered when WebDriverIO attempted to connect to Appium due to a lack of compatible capabilities

I'm currently facing an issue while attempting to link my virtual Android Device through Appium with my Webdriverio script for the purpose of automating some testing tasks. Here are the capabilities that I have set: capabilities: [{ // N ...

Simultaneous opening of several bootstrap collapse panels with a single button press

I have been developing a blog-style web application with Django. My goal is to display all the posts on the home page, with each post containing a collapse panel. Initially, I had hardcoded the IDs to trigger the collapse panels, causing all the panels to ...