I have a div, absolutely positioned, originally non-visible that is shown at the position of an element icon (in elements listing) being clicked rendering its preview (top position of the preview is lined to the top of the icon clicked).

When the element being clicked is positioned low on the page, the preview is rendered somewhat below the original page border, and scrolling is necessary.
I want to move the preview upward to have its bottom edge on the previous page bottom limit. The problem is the code I use doesn't return what is expected for the page height (it is greater than the sum of the preview height and the clicked-element top position).

Here's the code: file 1:

file 2:

Query.fn.setTopAtClickedElement = function (element) {
//original positioning    
this.css('top', element.offset().top + 'px');

// the troublesome part where the eventual correction should be done
if (element.offset().top + this.height() > jQuery(document).height())
    this.css('top', jQuery(document).height() - this.height() + 'px');
Similar happens when I use Math.max(document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight) for the measure of the document height as suggested on some link .

Here is the visual look of what I am trying to explain, and here's the jsfiddle .

Do you have any suggestions on how I should implement this troublesome part of the code?

Please tell me if you need if I wasn't clear enough.
Thank you very much for the time.