2

I have a site which used jquery 1.x.... Now, I have started using jquery 3.x in this site..... to solve any migration issues, I have installed JQMigrate.

One of the messages it shows in console window is "JQMIGRATE: jQuery.fn.offset() requires an element connected to a document".

I am not sure how I can solve it. The only thing that is said as a "solution" is: "Do not attempt to get or set the offset information of invalid input."

That is obvious, but what does it mean in practice? if I have, for example,

var parentOffset = $offsetParent.offset();

Should I write that line something like this?

var parentOffset = $offsetParent ? $offsetParent.offset() : 0;

Is it really necessary since I know that $offsetParent is always a valid input.

Regards Jaime

jstuardo
  • 3,901
  • 14
  • 61
  • 136

2 Answers2

2

I just came across this same line of code.

The problem here is that the $offsetParent element is not part of the document.

Instead of checking $offsetParent.length we want to make sure this element is actually part of the document

// As of jQuery 3.0, .offset() only works for elements that are currently
// in the document. In earlier versions, this would return the value below
// but in jQuery 3.0 this throws an error.
var parentOffset = {top: 0, left: 0};

// If the element is in the document we are safe to use .offset()
if(document.body.contains($offsetParent[0])) {
    parentOffset = $offsetParent.offset();
}

See https://github.com/jquery/jquery-migrate/blob/master/warnings.md#jqmigrate-jqueryfnoffset-requires-an-element-connected-to-a-document for more information on this change.

Kevin Morse
  • 244
  • 2
  • 13
0

if(jQueryObject) will always be truthy even if a match doesn't exist for the selector or method used to obtain the element

Check it's length instead

var parentOffset = $offsetParent.length ? $offsetParent.offset() : 0;
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • I know, but that does not answer the question. The question is whether it is necessary to do that in jquery 3.0 even when I know that I am sure $offsetParent is always a valid input or can I safely ignore that warning? – jstuardo Aug 03 '18 at 23:49
  • i've never tried getting offset of an element that doesn't exist. According to error it seems it is – charlietfl Aug 03 '18 at 23:50
  • That is only a warning shown by JQMigrate.... it is not an error. It happens when I started using jQuery 3.0.... application still works, however, I think it is not good to have JQMigrate warnings without solution. The question is to know which is the best way to solve that migration issue. – jstuardo Aug 04 '18 at 00:27
  • You mean when I changed to jquery 3.0? – jstuardo Aug 04 '18 at 00:35
  • @charlietfl the warning still shows up even when $offsetParent.length is 1 – Kevin Morse Jul 16 '19 at 07:30
  • The problem here is that the $offsetParent element is not part of the document – Kevin Morse Jul 16 '19 at 07:52