Jai
Jai

Reputation: 2204

how can i make jquery toggleClass animate children to appropriate classes just like css-transitions do?

say i have the classes:

.box {  background:red; }
.box .mini-box { background:green; }

.box.active {  background:purple; }
.box.active .mini-box { background:yellow; }

if i was using css-transitions i would simply add transition:all 0.5s ease; and when the class active is added both elements would animate appropriately.

If I apply the jQuery toggleClass with an animation time, (without any css-transitions enabled) it only animates the targeted element. (i.e. .box).

$('.box').toggleClass('active', 500);

This does not happen with jquery ui's toggleClass method when i apply it to the parent method. Is there a way to make it behave as the css transitions would?

You can see the problem here: http://jsfiddle.net/yg8rz/1/ Second (mini) box is not transitioning colours.

You can see the desired result here: http://jsfiddle.net/yg8rz/4/ You must be using a webkit browser for it to work (in this instance).

NOTE: In the interests of better css practice (leaning towards a future without javascript transitions) it is important that the elements inherit the active class from ancestors rather than directly applying an active class to any child elements.

It's also important that this solution use javascript so that is works in ie8+

Upvotes: 2

Views: 648

Answers (1)

Goran Obradovic
Goran Obradovic

Reputation: 9051

The problem you are experiencing is caused by .mini-box (judging from your selectors) being inside of .box. When you apply transition to your .box element, it works as it should, but your .mini-box is not selected at all by your .box.active .mini-box selector, because .box does not have .active class until transition completes.

You can make an workaround like this

HTML:

    <div class="box">normal 1</div>
    <div class="box">
        normal 2
        <div class="box mini-box">
            mini
        </div>
    </div>

CSS:

.box {  background:red; }
.box .mini-box, .box.mini-box { background:green; }

.box.active {  background:purple; }
.mini-box.active { background:yellow; }

Fiddle: http://jsfiddle.net/yg8rz/3/

You will need to apply transition to both .box and .mini-box elements, I changed css classes so the same jQuery code also selects mini box and adds .active to it too.

It is either this, or adding css transitions to your classes. You can cover all (major) browsers with:

-webkit-transition: all 0.5 ease;
-moz-transition: all 0.5 ease;
-o-transition: all 0.5 ease;
transition: all 0.5 ease;

You can make only non-transition-supporting browsers use javascript with Modernizr:

$(".box").toggleClass("active");
if(!Modernizr.csstransitions){
    $(".mini-box").toggleClass("active", 500);
}

http://jsfiddle.net/yg8rz/10/

Upvotes: 1

Related Questions