Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript error: Uncaught TypeError: Cannot read property 'left' of undefined

This is a really annoying error and there seems to be various questions about this console error. It doesn't give me a whole lot to work with in the console using chrome.

 /**
     * Dropdown menu positioning
     */
    loc.dropMenuPositioning = function (){
        var dropMenu = $('.js-dropdown-item-wrap');
        var mainNavigationOffset = $('.js-nav-container > ul').offset();
        var mainNavigationPosition = mainNavigationOffset.left;
        dropMenu.css({'left' : mainNavigationPosition - 60});
    };

Sorry, i don't have much more to go with on this question. Any help would be greatly appreciated. Thank you.

like image 996
Singleton Avatar asked Feb 09 '16 18:02

Singleton


3 Answers

You are reading the property left from an object returned in the previous row. The line that fails is:

var mainNavigationPosition = mainNavigationOffset.left;

The error means that mainNavigationOffset is undefined.

Because mainNavigationOffset is set as:

var mainNavigationOffset = $('.js-nav-container > ul').offset();

it is possible that jquery was not able to get the offset of the element $('.js-nav-container > ul').

As stated by the jquery documentation:

Note: jQuery does not support getting the offset coordinates of hidden elements or accounting for borders, margins, or padding set on the body element.

While it is possible to get the coordinates of elements with visibility:hidden set, display:none is excluded from the rendering tree and thus has a position that is undefined.

Check that the element is actually visible.

Another option (that seems what really happened) is that the jquery expression:

$('.js-nav-container > ul')

is not returning any element.

To see if the element is visible, you can use the chrome dev tool:

display must not be equals to none display should not be equals to none

visibility must be equals to visible visibility should be equals to visible

Or you can simply execute in the console:

$('.js-nav-container > ul').css("display");
$('.js-nav-container > ul').css("visibility");
like image 152
Marco Altieri Avatar answered Nov 15 '22 16:11

Marco Altieri


Try this, jQuery doc

dropMenu.offset({ left: mainNavigationPosition - 60 });

Otherwise, you might need to set the position to absolute or relative:

link

like image 41
phenxd Avatar answered Nov 15 '22 15:11

phenxd


Check if your jQuery version is up to 1.2, the .offset() method may not work in older versions.

jQuery 1.2 change log

like image 1
Marvin Medeiros Avatar answered Nov 15 '22 16:11

Marvin Medeiros