Animating the background of a div element using jQuery

I am facing an issue with the code snippet below that I have written. It doesn't seem to be working as expected and I'm curious if anyone knows why.

The problem is that I have set a background color on the DIV, but when hovering over it, I want it to animate to a new color and then revert back to the original color when the mouse moves out. It works fine if I use opacity instead of colors.

<div class="blue">this is the content area</div>

<style>
.blue { background: #006699; }
</style>

<script>
$(document).ready(function(){
  $(".blue").hover(
    function() {
      $(this).animate({ backgroundColor:'#003d7b' }, 1000);
    },
    function() {
      $(this).animate({ backgroundColor:'#006699' }, 1000); 
    });
});
</script>

Appreciate any help!

Answer №1

It is not possible to animate the background color by default in jQuery due to the lack of included easing.

For more information, you can refer to this post: jQuery animate backgroundColor

You don't need to include the entire jQuery UI library, just the background color easings.

(function(d){d.each(["backgroundColor","borderBottomColor","borderLeftColor","borderRightColor","borderTopColor","color","outlineColor"],function(f,e){d.fx.step[e]=function(g){if(!g.colorInit){g.start=c(g.elem,e);g.end=b(g.end);g.colorInit=true}g.elem.style[e]="rgb("+[Math.max(Math.min(parseInt((g.pos*(g.end[0]-g.start[0]))+g.start[0]),255),0),Math.max(Math.min(parseInt((g.pos*(g.end[1]-g.start[1]))+g.start[1]),255),0),Math.max(Math.min(parseInt((g.pos*(g.end[2]-g.start[2]))+g.start[2]),255),0)].join(",")+")"}});function b(f){var e;if(f&&f.constructor==Array&&f.length==3){return f}if(e=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(f)){return[parseInt(e[1]),parseInt(e[2]),parseInt(e[3])]}if(e=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(f)){return[parseFloat(e[1])*2.55,parseFloat(e[2])*2.55,parseFloat(e[3])*2.55]}if(e=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(f)){return[parseInt(e[1],16),parseInt(e[2],16),parseInt(e[3],16)]}if(e=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(f)){return[parseInt(e[1]+e[1],16),parseInt(e[2]+e[2],16),parseInt(e[3]+e[3],16)]}if(e=/rgba\(0, 0, 0, 0\)/.exec(f)){return a.transparent}return a[d.trim(f).toLowerCase()]}function c(g,e){var f;do{f=d.css(g,e);if(f!=""&&f!="transparent"||d.nodeName(g,"body")){break}e="backgroundColor"}while(g=g.parentNode);return b(f)}var a={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0],transparent:[255,255,255]}})(jQuery);

Answer №2

Revision

$(this).animate({ backgroundColor:'#003d7b' }, 1000);

REVISED TO

$(this).animate({ background-color:'#003d7b' }, 1000);

The hyphen was missing.

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

Refresh the jQuery Raty choice when clicked (jQuery)

Currently, I am incorporating the jQuery Raty plugin into a jQuery UI dialog to create a questionnaire-style format. Through custom jQuery scripting, I have devised an interactive interface where users are presented with a new question upon each selection ...

Executing functions with iterations

Can anyone help me understand why my buttons always output 100 in the console log when clicked? Any ideas on how to resolve this issue? function SampleFunction(param){ console.log(param); } for (i = 0; i < 100; i++) { $("#btn-" + i).on('c ...

What is the best way to embed sections of one HTML page into another page?

Is there a method I can use to embed sections of one webpage within another webpage? The dilemma arises from the fact that the second page has a distinct style compared to my main page. Is it feasible to apply the alternate style solely to specific content ...

The integration of signalR with jquery mobile is posing several challenges

Recently, I started working with jquery mobile and signalR to implement a calling feature in my mobile app. However, I encountered an error that looks like this: http://localhost:2286/signalr/negotiate?clientProtocol=1.5&connectionData=%5B%7B%22name%2 ...

How to resolve CORS error when using custom request header in Django with JavaScript and redirecting to OPTIONS request?

I am currently working on building an API library using Django. This API will be accessed by javascript, with the Django-API and javascript running on separate servers. The Django API library requires a custom request header from the javascript front end, ...

I would like to have the div completely fill the page on my website

How can I make a div fill the entire height of my website using Bootstrap? I want to ensure that the div extends all the way down Please provide guidance on how to accomplish this. ...

Customizing the color of buttons in MUI 4

Currently, I am utilizing mui V4 for my styling and attempting to incorporate an additional color for my buttons. I understand that it only accepts these predefined colors: expected one of ["default", "inherit", "primary", "secondary"]. To achieve this, I ...

Can the information from a form be automatically submitted to the server upon selection?

<div class="modal-body modal-body-step-2"> <form action="prenotazioni.php" method="post"> <div class="input-group"> <input type="radio" name="spettacolo" value="Lo Schiaccianoci">Lo Schiaccianoci<br> ...

Adjust the size of an image within a container in real-time with jQuery

In my coding project, I have a div element called "content_container" that is designed to be draggable and resizable using jQuery UI. Within this container, I have integrated TinyMCE, a content text editor. My current challenge involves the scenario where ...

What is the best way to overlay text onto a background image using Material UI's Card and CardMedia components?

Using the card component, I have successfully added a background image. However, I am facing difficulty in figuring out how to overlay text on top of this image. If anyone has suggestions or alternative methods, please feel free to share! <Card> ...

How can I make the Struts2 iterator function correctly?

Using the Struts2 <iterator> tag in a JSP to display values, the method is being called but no results are appearing on the page. All the necessary data is printing in the console, but not in the JSP itself. The call made is localhost\listAddCo ...

Steps to modify the CSS of a custom component in Angular 8

I have been attempting to override the css of a custom component selector, however, my attempts have been unsuccessful. I have tried using ":ng-deep" but it hasn't worked. How can I go about finding a solution for this issue? app.component.html: < ...

Tips for maintaining consistent webpage layout across various screen sizes

Although this method may seem outdated, I have always been intrigued by how it was accomplished. In the past, before websites became responsive, pages would simply shrink down to fit on mobile devices without adjusting their appearance. How was this achie ...

Angular validation with input binding using if statement

I have developed a reusable component for input fields where I included a Boolean variable called "IsValid" in my typescript file to handle validation messages. Here is the code from my typescript file: export class InputControlsComponent implements OnIn ...

The webpage appears fine on the local server, but displays incorrectly on IIS (Internet Explorer 11)

My project looks great when I run it locally on my computer and open the page in Internet Explorer 11: https://i.stack.imgur.com/yZvo2.png However, when I deploy the page to an IIS server and navigate to the page, it appears differently in Internet Explo ...

Elevate your website with a mesmerizing CSS effect: watch

I am trying to achieve a CSS3 effect where an image slides up when hovered over, similar to this. I came across this example, but I do not want to use the box's background property. <div class="box"> <img src=image/image.jpg> & ...

Sending the method's URL in the controller through an AJAX call

Below is the code snippet for an ajax call: <script> jQuery(document).ready(function() { $("#VEGAS").submit(function(){ var form_data = $("#VEGAS").serialize(); var routeUrl = "<?= url('/'); ?> /PUBLIC/vpage"; $.ajax({ ...

The thickness of an SVG line increases as it is rotated

I am working with multiple straight lines and have specified the stroke-width as 4. However, when I attempt to rotate them, the lines appear thicker than expected. Additionally, setting a negative value, such as <path d="M0 -10 20 0" stroke-width="4" st ...

Using Jquery to find the class that matches the current element

Is it possible to select a specific div by its class when there are multiple divs sharing the same class and triggering the same function on button click? I only want to target the class where $(this) is located. I've experimented with .parent, .chil ...

Choosing <label> elements, while disregarding those <label> elements that include <input>

I need assistance with CSS rules to target only <label> elements that do not contain an <input> field inside of them. Is there a specific rule I can use for this? <label for="type">Regular Label</label> <label for="type"> ...