Reputation: 15772
Reopening bounty as forgot to award it last time. Already being answered by Master A.Woff.
I want to reach to a certain row when a user expands it (so that when last visible row gets expanded, the user doesn't have to scroll down to see the content).
I used,
$('#example tbody').on('click', 'td .green-expand', function (event, delegated) {
var tr = $(this).closest('tr');
var row = table.row(tr);
if (row.child.isShown()) {
if (event.originalEvent || (delegated && !$(delegated).hasClass('show'))) {
row.child.hide();
tr.removeClass('shown');
}
} else {
if (event.originalEvent || (delegated && $(delegated).hasClass('show'))) {
row.child(format(row.data())).show();
tr.addClass('shown');
var parent = $(this).closest('table');
var scrollTo = $(this).closest('tr').position().top;
$('.dataTables_scrollBody').animate({
scrollTop: scrollTo
});
}
}
});
Note
Expand row - just click on click
hyperlink. It will show row details
Upvotes: 19
Views: 1163
Reputation: 74410
You should use offsetTop
property instead to get relevant offsetParent
(see edit part):
var scrollTo = tr.prop('offsetTop');
Or set table
element position not static:
table.dataTable { position: relative; }
EDIT: Why jq position().top
doesn't work in this case?
This is because position is calculated regarding offsetParent
. Natively, regarding spec, the offsetParent is the nearest ancestor with computed position not static or the body
element or td, th
or table
(spec).
This behaviour, i suspect, can return different result regarding browser implementation, following the spec or not.
So, jQuery normalizes it, not using native DOM property offsetParent
but own method $.fn.offsetParent()
. This method implementation is as follow:
offsetParent: function () {
return this.map(function () {
var offsetParent = this.offsetParent || docElem;
while (offsetParent && (!jQuery.nodeName(offsetParent, "html") && jQuery.css(offsetParent, "position") === "static")) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || docElem;
});
}
As you can see, no element exception is done regarding any type of element (docElem
is the current document object).
By default, table
element position is static, that's why in your example, jq returns as offsetParent
, the div
wrapper used by jQuery datatable plugin and not the table
(exception following spec). And so, native offsetTop
property and jq $.fn.position().top
returns different result.
Also the currently solution does not work in all cases
Testing it on chrome (only), i cannot replicate issue.
Upvotes: 11
Reputation: 61
You will need to take the screen height and adjust the expanded div as per your required pixel size. We cannot directly use the scrollTop option to adjust the position in the window. These have to dynamically adjusted since it depends on various screen resolutions and sizes. See if you have more issues.
Thanks!!
Upvotes: 1