3

I have a situation where I need to delete the top-most divs in a document without causing any changes from the user's perspective. Basically, I need to go from:

---------top of document
div1
div2
div3
---------top of window
div4
div5
---------bottom of window
div6
div7
---------bottom of document

to:

---------top of document
div3
---------top of window
div4
div5
---------bottom of window
div6
div7
---------bottom of document

What would be the best way to accomplish this transition in a manner that doesn't cause the user to see div4 and div5 make any movement?

Danny Guo
  • 892
  • 1
  • 14
  • 28

3 Answers3

2

You should be able to set the document's scrollTop to the current one minus the height of the divs you are removing. Something like:

var height = $('#div-1').height() + $('#div-2').height();
$(document).scrollTop($(document).scrollTop() - height);
$('#div-1, #div-2').remove();

The change in scroll position should be fast enough that the user won't notice it.

Andrew Burgess
  • 5,300
  • 5
  • 30
  • 37
1

Heavily edited!

$( document ).ready(function() {
    var heightof = $('#one').height() + $('#two').height();
    $(window).scroll(function(){
        var y = $(this).scrollTop();

        if(y >= heightof)
        {
            $('#one, #two').remove();
            $(this).scrollTop('0px');
        }
    });  
});

Here, this should work!

This code is basically checking for scroll event, and when it reaches past the first two divs (so we add their heights), we remove them. I didn't even noticed anything changes when I tested them.

check it out live on jsfiddle

Azeem Bande-Ali
  • 305
  • 2
  • 8
Craftein
  • 762
  • 5
  • 10
  • But in this case, wouldn't the user still see a blank space if he or she scrolled up? That's why I want the top of the document to be the top of div3. – Danny Guo Feb 09 '14 at 04:16
  • not unless you resize div 3 or do some manipulation to it. that's why a parent div can help you a lot in doing so. and there's many way to do it, but i don't know what else you need... talking about the looks, contents, or whatever related that might affect the presentation – Craftein Feb 09 '14 at 04:19
  • @user1481479 here you go. – Craftein Feb 09 '14 at 04:44
  • Works! Thank you. Only problem is that there is a lag on iOS. But that appears to be because of this issue: http://stackoverflow.com/questions/10482227/javascript-dom-changes-in-touchmove-delayed-until-scroll-ends-on-mobile-safari – Danny Guo Feb 09 '14 at 04:50
0

If you don't need to actually remove the element from the DOM, you can set its style.visibility property to "hidden". It will disappear from the page, but there will still be an empty space where it used to be.

Dan Hlavenka
  • 3,697
  • 8
  • 42
  • 60
  • Unfortunately, I do need to actually remove it from the DOM, and I can't have an empty space in place of divs 1 and 2. The top of document should end up as the top of div3. – Danny Guo Feb 09 '14 at 04:12