Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the height of a menu on page load

Tags:

jquery

I'm trying to set a menu, and with:

var headed = $('#menu-main_menu li');
headed.hover(
    function() {
        var subed  = $(this).find('ul.sub-menu').height();
        var headwi = $(this).width();
        $(this).find('ul.sub-menu').css({'top': -subed, 'width': headwi }).show();
    }, 
    function() {
        $(this).find('ul.sub-menu').hide();
        return false;
    }
);

Here is a jsfiddle example : http://jsfiddle.net/moabi/VDZYV/2/ and as you can see, it doesn't get the height on the first shot. What did i do wrong ? (the menu is at the bottom of the page, so I want the sub-menu to go up, this is why i put the negative value) thank you

like image 619
moabi Avatar asked Nov 22 '25 22:11

moabi


1 Answers

It's because your sub menu items are floating next to each other in a horizontal line by default, so initially the height of the sub menu is only the height of one of the items, not all added together.

If you set the width of the sub menu first then its height will be correct as the items will have stacked, so something like:

headed.hover(function() {

    var subm = $('ul.sub-menu', $(this)).show();
    subm
        .width($(this).width())
        .css('top', -subm.height());

}, function() {
    $('ul.sub-menu', $(this)).hide();
    return false;
});

What might be easier though is to tweak the CSS so the sub menu items stack vertically naturally, so:

#access .menu-header .sub-menu li
{
float: none;
}
like image 99
Ian Routledge Avatar answered Nov 24 '25 11:11

Ian Routledge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!