I’m writing a site and using jQuery. I’ve got an issue where I want to do two distinct changes to the DOM. Basically, I’m calling $.toggle() on a couple of divs, one of which is hidden, and the other is visible.
<div>
<button onclick='javascript:$(".panel").toggle()'>Toggle!</button>
<div class="panel">Content1</div>
<div class="panel hide">Content2</div>
</div>
The problem I have is that the browser is re-rendering the page after each call to toggle(). This switch is invisible to the naked eye, but results in some strange behaviour.
What ends up happening is that the first .panel div is found, and that is toggled to be hidden. The second .panel div is then toggled, and is shown. In between these calls, the browser detects a DOM change and re-renders the page with both divs hidden.
If these divs are at the bottom of a page, the page becomes shorter for a fraction of a time, so the page scroll position jumps up before the second div becomes visible.
Flipping the visibility back the other way doesn’t have the same effect, because now the browser briefly renders the page with both divs visible, before hiding the second div. There’s no scroll issues then.
Is it possible to somehow place some sort of hold or lock over these two actions to instruct the browser not to reflow, scroll, or otherwise render the page until the hold/lock has been released? In that case, the browser would render the page with a single .panel, the javascript would run and the browser would then be instructed to re-render the changed DOM.
Edit
I’ve added a JSFiddle of what I mean over at http://jsfiddle.net/3Kvqh/1/ Simply browse to the bottom of the page and hit ‘toggle’, and watch the scroll be weird.
Further testing reveals that this only occurrs in Chrome. The plot thickens.
After better looking at my other answer, I think it will work for the first time but fail when you execute it a second time. So I’ve take a different approach here, this code will always work fine:
I’m taking advantage of jquery visibility filters to always firstly toggle the hidden divs later the visible ones.