JavaScript error: Uncaught TypeError: Unable to read property "left" from undefined

This is a really annoying bug, and there seem to be various questions about this console error. It does not give me much work to work with 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 have no more questions on this. Any help would be greatly appreciated. Thanks.

+5
source share
3 answers

You are reading the property left over from the object returned in the previous line. Invalid line:

 var mainNavigationPosition = mainNavigationOffset.left; 

An error means that mainNavigationOffset is undefined.

Since mainNavigationOffset is set as:

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

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

As stated in the jquery documentation:

Note: jQuery does not support getting the offset coordinates of hidden elements or taking into account the borders, margins or indents set on a body element.

So far, you can get the coordinates of the elements with visibility: hidden set, display: none are excluded from the rendering tree and, therefore, has an undefined position.

Make sure the item is actually visible.

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

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

does not return any item.

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

the display should not equal any the display should not equal anyone

visibility should be equal to visible visibility should be equal to visible

Or you can simply execute in the console:

 $('.js-nav-container > ul').css("display"); $('.js-nav-container > ul').css("visibility"); 
+3
source

Try this, jQuery doc

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

Otherwise, you may need to establish an absolute or relative position:

link

+1
source

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

jQuery 1.2 change log

+1
source

Source: https://habr.com/ru/post/1242641/


All Articles