user1184100
user1184100

Reputation: 6894

Animate and simultaneously add class to li

I wanted to animate a block of div and also at the same time add class to li, How can i do this?

My fiddle - http://jsfiddle.net/AsfFQ/4/

When i click the div in 'red' background, it will animate 0px to left. How add a class "selected" to li's for every 20px of animation of the div.

Upvotes: 0

Views: 202

Answers (2)

adeneo
adeneo

Reputation: 318312

If using the new jQuery 1.8, you can actually perform an animation and get a promise back, the returned object also contains the animated state, tween etc, and you can use that to calculate what element to apply the class to, this is kinda experimental, and I just started playing around with this, but something like :

$(function() {
    $('.block').on('click', function(){
        var ani = $.Animation( this, {left:0}, {duration: 1000} );

        ani.progress(function(e) {
            var Now = e.tweens[0].now,
                idx = Math.round(Now/10);
            $(".container ul li").eq(idx).addClass('selected').siblings().removeClass('selected');
        });
    });    
});    

FIDDLE

Upvotes: 2

Brian Ustas
Brian Ustas

Reputation: 65559

Have a look at this DEMO.

Here's the Javascript:

var timer, 
    selectLi = (function() {
        var $block = $('.block'),
            $container = $('.container'),
            $lis = $('.container ul li'),
            liWidth = $lis.width(),
            $selectedLi;

        return function() {
            var pos = $block.offset().left - $container.offset().left,
                liNum = Math.round(pos / liWidth);
            $selectedLi && $selectedLi.removeClass('selected');
            $selectedLi = $($lis.get(liNum));
            $selectedLi.addClass('selected');
        };
    })();

$('.block').click(function() {
    timer = setInterval(selectLi, 30);
    $(this).animate({
        left: 0
    }, function() {
        clearInterval(timer);
    });
});

Upvotes: 0

Related Questions