slimcady
slimcady

Reputation: 109

jquery animate ul by list item

I have a ul that I want to center vertically to the vertical center of another element based upon the li that a user clicks. I have some code worked up here:

http://jsfiddle.net/XxmAT/1/

But it is unfortunately not behaving how I would like it to, I know my math is off, so any help would be much appreciated!

Upvotes: 2

Views: 548

Answers (2)

Nick Benedict
Nick Benedict

Reputation: 557

here you go. Got the height of the li and multiplied it to account for the height of the space between li and then multiplied by the index that was clicked.

http://jsfiddle.net/XxmAT/36/

        var u_menu = $("#menu-main-menu").position().top;
        var z_menu = $("#menu-main-menu").height();

        var y = $("#box1").offset().top;
        var z = $('#box1').height();


        var c_menu = (z_menu / 2) ;


        $("#menu-main-menu").css('top', - c_menu);


        $('ul#menu-main-menu li').click(function (e) {
        // this is the dom element clicked
        var index = $('li').index(this);


         var x = $('li').height() * 2;

         var offset_li = (u_menu + y) / index  ;

        $('ul#menu-main-menu').animate({top: -(x*index)}, "slow")


    });​

Upvotes: 0

Hidde
Hidde

Reputation: 11951

I think this one is prettier:

http://jsfiddle.net/XxmAT/33/


Usually it is best to think of the logic first, and start making variables after. Because of the cluster of variables, it was hard to understand what you meant with all the code. The click function just got a lot simpeler, and it is easier to understand what I am subtracting from which number, to get the desired result...

Sidenote: The - 180 at the end is probably the strange (and enormous) margin.

Upvotes: 3

Related Questions