Animate blur filter
Asked Answered
J

4

17

Is it possible to animate the CSS3 blur filter using jQuery?

This works as a static way of applying CSS rules :

item.css({'filter': 'blur('+blur+')','-webkit-filter': 'blur('+blur+')','-moz-filter': 'blur('+blur+')','-o-filter': 'blur('+blur+')','-ms-filter': 'blur('+blur+')'});

but when I replace the css method with the animate method, nothing happens.

item.animate({'filter': 'blur('+blur+')','-webkit-filter': 'blur('+blur+')','-moz-filter': 'blur('+blur+')','-o-filter': 'blur('+blur+')','-ms-filter': 'blur('+blur+')'},500);

Is there a trick I'm unaware of? How can I animate the blurriness of an item?

Jaws answered 19/11, 2013 at 21:20 Comment(2)
its not worth it, blur is still too slow, even with css transitionsLadle
It may be slow, I don't need it to animate afterwards, its just staying thereJaws
C
22

You can use the .animate() function on a variable that is of numerical value, and animate accordingly - call a function during each step and assign that new numerical value as a CSS filter blur radius property :)

$(function() {
    $({blurRadius: 0}).animate({blurRadius: 10}, {
        duration: 500,
        easing: 'swing', // or "linear"
                         // use jQuery UI or Easing plugin for more options
        step: function() {
            console.log(this.blurRadius);
            $('.item').css({
                "-webkit-filter": "blur("+this.blurRadius+"px)",
                "filter": "blur("+this.blurRadius+"px)"
            });
        }
    });
});

Minor update: jQuery's .animate() might not tween to the final value correctly, as noted in another answer below. In this case, it is always safer to chain a callback that manually sets the blur radius to the intended final value. I have modularised the functions so that it can be reused without too much redundancies:

$(function() {
        // Generic function to set blur radius of $ele
    var setBlur = function(ele, radius) {
            $(ele).css({
               "-webkit-filter": "blur("+radius+"px)",
                "filter": "blur("+radius+"px)"
           });
       },

       // Generic function to tween blur radius
       tweenBlur = function(ele, startRadius, endRadius) {
            $({blurRadius: startRadius}).animate({blurRadius: endRadius}, {
                duration: 500,
                easing: 'swing', // or "linear"
                                 // use jQuery UI or Easing plugin for more options
                step: function() {
                    setBlur(ele, this.blurRadius);
                },
                callback: function() {
                    // Final callback to set the target blur radius
                     // jQuery might not reach the end value
                     setBlur(ele, endRadius);
                }
            });
        };

    // Start tweening
    tweenBlur('.item', 0, 10);
});

You can see this updated code in action in the attached code snippet below.


It is important to note that Firefox (FF ≥35 and above supports unprefix CSS filters), IE and Opera has no support for CSS3 filters, so there is no need to use -moz-, -ms- or -o- prefixes :)

See fiddle: http://jsfiddle.net/teddyrised/c72Eb/ (prior to update)

See code snippet below for the most up-to-date example:

$(function() {
        // Generic function to set blur radius of $ele
    var setBlur = function(ele, radius) {
            $(ele).css({
               "-webkit-filter": "blur("+radius+"px)",
                "filter": "blur("+radius+"px)"
           });
       },
       
       // Generic function to tween blur radius
       tweenBlur = function(ele, startRadius, endRadius) {
            $({blurRadius: startRadius}).animate({blurRadius: endRadius}, {
                duration: 500,
                easing: 'swing', // or "linear"
                                 // use jQuery UI or Easing plugin for more options
                step: function() {
                    setBlur(ele, this.blurRadius);
                },
                complete: function() {
                    // Final callback to set the target blur radius
                    // jQuery might not reach the end value
                    setBlur(ele, endRadius);
               }
           });
        };
    
    // Start tweening towards blurred image
    window.setTimeout(function() {
        tweenBlur('.item', 0, 10);
    }, 1000);
    
    // Reverse tweening after 3 seconds
    window.setTimeout(function() {
        tweenBlur('.item', 10, 0);
    }, 3000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item">
    <p>Sample text that will be blurred.</p>
    <img src="http://placehold.it/500x500" />
</div>
Cancroid answered 19/11, 2013 at 21:32 Comment(2)
as of today, FF 35 applied filter without prefix and this should work on every thing nowStain
@AamirMahmood Thanks for the heads up! That's really good to know :) now we are left with IE and Opera, heh.Cancroid
T
13

One Google Search query gave me this result you might wanna take a look at. What I suggest to do is only toggle a class in your JS and handle the rest in your CSS, for instance:

var $item = $('.item'); // or any selector you want to use
$item.addClass('item--blur');

Handle the rest in your CSS:

.item {
    transition: all 0.25s ease-out;
}
.item--blur {
    // all your filters
}
Treillage answered 19/11, 2013 at 21:29 Comment(1)
this works, but not in my case as I'm already using css animations in another scope. but thanks!Jaws
T
2

I tried Terry's answer, which worked great until I tried reversing the process to animate the removal of the blur effect. Instead of ending with a blur of 0, the process ended with a blur of 0.0815133px. Most browsers seemed to round this down to zero, but iOS didn't and left a noticeable blur on the page. Following the animated change by manually setting the blur to zero fixed this:

$('.item').css({
  "-webkit-filter": "blur(0)",
  "filter": "blur(0)"
});
Telfore answered 19/7, 2016 at 21:8 Comment(1)
Yeah, sometimes jQuery's animation do not actually arrive at the final value precisely. You can set a callback function to ensure that the blur radius is set to the final intended value :) also updated my answer, thanks for the heads up!Cancroid
S
0

try this simple solution:

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}
async function applyBlurFilter() {
    for (var i = 1 ; i <= 100; i++) {
        $('h1').css({ "filter": "blur(" + i/10 + "px)" });
        await sleep(40); //4 seconds (40 * 100 / 10)
    }
}

$(document).ready(function(){
  applyBlurFilter();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>
  This Text is going to be blured. 
</h1>
Spotweld answered 3/3, 2020 at 19:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.