Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reposition drop down menu if near edge of window

I'm using the following code to reposition my drop down menus if they fall outside of the browser window area. However it does not work in Internet Explorer 7 and 8.

jQuery(document).ready(function(){
    jQuery("#nav>ul>li").each(function() {
        pos = jQuery(this).offset();
        if(pos.left + 100 > jQuery(window).width()+window.pageXOffset-jQuery(this).width()) {
        jQuery(this).addClass("nav-shift");}
    });
});
like image 540
GhostPool Avatar asked Oct 21 '25 10:10

GhostPool


1 Answers

The window.pageXOffset property is not supported in IE (7 and 8, at least). Try $(window).offset().left instead:

jQuery(document).ready(function(){
    jQuery("#nav>ul>li").each(function() {
        pos = jQuery(this).offset();
        if(pos.left + 100 > jQuery(window).width()+jQuery(window).offset().left-jQuery(this).width()) {
        jQuery(this).addClass("nav-shift");}
    });
});

More readable, IMO:

jQuery(document).ready(function() {
    jQuery("#nav > ul > li").each(function() {
        var $this = jQuery(this),
            $win = jQuery(window);

        if ($this.offset().left + 100 > $win.width() + $win.offset().left - $this.width()) {
            $this.addClass("nav-shift");
        }
    });
});
like image 117
jensgram Avatar answered Oct 24 '25 09:10

jensgram



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!