Reputation: 453
I have a div element with lots of content inside:
<div id="x" class="unhidden">
text and more divs
</div>
The CSS class 'unhidden' contains:
display: block;
When I click on a link, the element id='x' becomes class='hidden' trough javascript, which contains:
display: none;
The div element is now hidden. So far so good. Now I want to go back and show the full div='x'
and scroll down to a certain div in div id='x'
.
So when I click on the back button, first the class becomes unhidden
again trough javascript and after that I run this script in the same function:
window.scroll(0, findPos(document.getElementById(GoTo)));
GoTo is the ID of a certain div I want to scroll down to. With this function doing the scroll down:
function findPos(obj) {
var curtop = 0;
if (obj.offsetParent) {
do {
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
return [curtop];
}
}
The script does find the position of where to go to, but doesn't scroll down.
The scroll down script also works if it is separated from the hidden/unhidden part. But here it doesn't work, the hiding/showing part blocks something.
Any solutions, or thoughts?
Upvotes: 1
Views: 899
Reputation: 96383
I think this is due to the browser executing all of your JS code first, before it gives control back to the rendering engine – so changing the class has not actually made the element visible again at the point where your code to calculate the element position is executed (and elements that are not displayed do not have any position).
If you wrap your whole window.scroll
call into an anonymous function and execute that with a minimal delay using setTimeout
, that should solve the problem:
referenceToDivElement.className = "unhidden";
var targetElement = document.getElementById(GoTo);
window.setTimeout(function() {
window.scroll(0, findPos(targetElement));
}, 5);
Upvotes: 1