Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Modernizr and jQuery to Animate if CSS3 Transitions Don't Exist

Is there a way to use a combination of Modernizr and jQuery to enable something similar to transitions if CSS3 isn't supported? What I'm currently doing is like this...

<div class="hoverable">
 <p>This div changes both width and height on hover</p>
</div>

The CSS is

.hoverable {
 height: 100px;
 width: 2000px;
 transition: height .5s, width .5s;
}

.hoverable:hover {
 height: 200px;
 width: 100px;
}

I'm currently just using Modernizr to make the div be in the hover state by default if CSS3 transitions aren't supported. Is there a way to use Modernizr to trigger jQuery animation if CSS3 isn't supported? If not jQuery, then I'd be fine using custom animation, too, but I don't really know how to do either.

like image 685
JacobTheDev Avatar asked May 23 '11 14:05

JacobTheDev


1 Answers

Solved this myself. The way I did was like this

<!doctype html>
<html>
    <head>
        <title>Modernizr + jQuery Testing</title>
        <script type="text/javascript" src="modernizr.js"></script>
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript">
        if(!Modernizr.csstransitions) { // Test if CSS transitions are supported
            $(function() {
                $('#js').hover(function(){
                    $(this).animate({width:'50px',height:'50px'},{queue:false,duration:500});
                }, function(){
                    $(this).animate({width:'100px',height:'100px'},{queue:false,duration:500});
                });
            });
        }
        </script>
        <style type="text/css">
            body {
                margin: 0;
                padding: 0;
            }
            div {
                border: 1px solid red;
                height: 100px;
                margin: 25px auto;
                width: 100px;
            }
            #css {
                transition: height .5s, width .5s;
                -khtml-transition: height .5s, width .5s;
                -moz-transition: height .5s, width .5s;
                -o-transition: height .5s, width .5s;
                -webkit-transition: height .5s, width .5s;
            }
            #css:hover {
                height: 50px;
                width: 50px;
            }
        </style>
    </head>

    <body>
        <div id="js">
            JS
        </div>
        <div id="css">
            CSS
        </div>
    </body>
</html>

That worked perfectly. The CSS one only animates in new browsers (because that's the only place it can) and the JS one only animates in old browsers. If you use this script, you can get modernizr from http://www.modernizr.com/ and jQuery from http://www.jquery.com/ (of course).

like image 90
JacobTheDev Avatar answered Oct 04 '22 21:10

JacobTheDev