Reputation: 109
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:
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
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.
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
Reputation: 11951
I think this one is prettier:
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