Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling a css3 transition from jquery

Tags:

jquery

css

CSS3 transitions are great! So far, I'm triggering them with :hover or :active declarations in the stylesheet. I'm looking to see if there's a way to trigger them from jquery.

For instance:

#MyDiv{
border:1px solid red;
background:blue;
transition: all 0.3s linear;
}

MyDiv:hover{
border:1px solid black;
background:yellow;
}

The :hover transition will trigger when the mouse moves over MyDiv but what I'm looking to do is something like:

$('#MyDiv').transition(hover); //that would be ideal

In other words, I'd like to trigger the css animation so that if I mouseover some other div, the #MyDiv animation will trigger with $('#SomeOtherDiv').mouseenter(function () { $('#MyDiv').transition(hover); });

The jquery animate function doesn't support color transitions and while I know you can add jqueryUI plugins to make it work, I was wondering if there's some way to make it work without, using jquery to call the css transition.

like image 396
frenchie Avatar asked Aug 16 '11 01:08

frenchie


Video Answer


2 Answers

#MyDiv {
    border:1px solid red;
    background:blue;
    transition: all 2.0s linear;
    -webkit-transition: all 0.3s linear;
    -moz-transition: all 0.3s linear;
    -ms-transition: all 0.3s linear;
    -o-transition: all 0.3s linear;
}

.hover{
    border:1px solid black;
    background:yellow;
    transition: all 2.0s linear;
    -webkit-transition: all 0.3s linear;
    -moz-transition: all 0.3s linear;
    -ms-transition: all 0.3s linear;
    -o-transition: all 0.3s linear;
}

$("#MyOtherDiv")
.mouseenter(function(){
    $("#MyDiv").addClass("hover");
})
.mouseleave(function(){
    $("#MyDiv").removeClass("hover");
});
like image 120
Scott Avatar answered Sep 27 '22 21:09

Scott


For better mobile device performance, I would use webkit-transform rather than webkit-transition since you are going to be getting the hardware acceleration benefits from the mobile device, resulting in a smoother, native look when performing these transitions using CSS3.

In fact, I'd go ahead and get the jQuery Transit plugin, which makes it easy to use jQuery to invoke a given transition. It basically takes care of the CSS3 transitions for you and gives cross-browser compatibility.

JS Fiddle Demo

Javascript:

$("#startTransition").on("click", function()
{
    $("#MyDiv").transition({ background: 'yellow', color: 'black'});
});
like image 45
Gaff Avatar answered Sep 27 '22 22:09

Gaff