Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to animate box-shadow with jQuery

Which is the correct syntax to animate the box-shadow property with jQuery?

$().animate({?:"0 0 5px #666"}); 
like image 394
chchrist Avatar asked Nov 09 '10 11:11

chchrist


People also ask

How do you animate in jQuery?

jQuery Animations - The animate() Method The jQuery animate() method is used to create custom animations. Syntax: $(selector). animate({params},speed,callback);

Can you animate box shadow CSS?

Adding a CSS transition to animate the box-shadow of an element is a handy trick. It's a design technique that's often used on hover to highlight something. If you've used this effect you might have noticed that sometimes the performance can be sub optimal making the animation slow.

Can you animate background color in jQuery?

The working of the jQuery background colour animate – Suppose we have a div element and we need to apply the background colour animation effects. So we can use the animate() function as “$('#bid'). animate({ backgroundColor: “gray”, color: “white” })”, which will change the background colour of the selected element.


1 Answers

Direct answer

Using Edwin Martin's jQuery plugin for shadow animation, which extends the .animate method, you can simply use the normal syntax with "boxShadow" and every facet of that - color, the x- and y-offset, the blur-radius and spread-radius - gets animated. It includes multiple shadow support.

$(element).animate({    boxShadow: "0px 0px 5px 3px hsla(100, 70%, 60%, 0.8)" });  

Using CSS animations instead

jQuery animates by changing the style property of DOM elements, which can cause surprises with specificity and moves style information out of your stylesheets.

I can't find browser support stats for CSS shadow animation, but you might consider using jQuery to apply an animation-based class instead of handling the animation directly. For example, you can define a box-shadow animation in your stylesheet:

@keyframes shadowPulse {     0% {         box-shadow: 0px 0px 10px 0px hsla(0, 0%, 0%, 1);     }      100% {         box-shadow: 0px 0px 5px 0px hsla(0, 0%, 0%, 0);     } }  .shadow-pulse {     animation-name: shadowPulse;     animation-duration: 1.5s;     animation-iteration-count: 1;     animation-timing-function: linear; } 

You can then use the native animationend event to synchronise the end of the animation with what you were doing in your JS code:

$(element).addClass('shadow-pulse'); $(element).on('animationend', function(){         $(element).removeClass('shadow-pulse');     // do something else... }); 
like image 95
iono Avatar answered Nov 09 '22 07:11

iono