0

I'm wondering if it is possible to "teleport" a div into another part of the DOM using jQuery on scrolling.

For example, let's say I have an article:

Title

Subt 1
Div area 1
Content 1

Where subt is subtitle and div area is where the div will be included.

So I need to achieve this result:

While the user will be scrolling, the div will be jumping from area to area

     **-- If I scroll from here --**

Subt 1
        Div area 1 
        Content 1



       Subt 2
        Div area 2
        Content 2



       Subt 3
        Div area 3
        Content 3


    **-- To here --**
       Subt 4
        Div area 4 -- The div will appear inside of here --
        Content 4

I don't want the div to appear at all places at once, it's just that it will follow the scrolling moving from one area to another one. I not even know how search this in google, that's why I'm asking.

Thx in advance

User325313
  • 79
  • 9
  • You're asking how [to move an element into another element](http://stackoverflow.com/questions/1279957/how-to-move-an-element-into-another-element) – adeneo Oct 08 '16 at 18:38
  • Yes, but only on scrolling. – User325313 Oct 08 '16 at 18:41
  • So you're also asking [how to do something on scroll](http://stackoverflow.com/questions/10994909/do-something-when-page-is-scrolling-and-have-some-position) ? – adeneo Oct 08 '16 at 18:42

1 Answers1

1

The method you'll want to use is jQuery's detach (https://api.jquery.com/detach/)

// Detach is to splice from the DOM
$SwappedElement = $('#HotSwapDiv').detach(); 
// substitute logic to determine div position by window scroll
$DestinationDivArea = $('#div_identifier)
// Append (attach to end) of Destination div
$DestinationDivArea.append( $SwappedElement );

You can listen to the window scroll event with the following, in jQuery:

$(window).scroll(function() {
  // Get current window scroll amount in pixels
  iPixelsScrolledFromTop = $(window).scrollTop();
  // Get the amount from the top of one of your divs
  iDivAreaPixelsFromTop = $('#div_identifier').offset().top;
  // Arbitrary calculation to see if target div is 250 pixels away from scroll
  if( iPixelsScrolledFromTop > (iDivAreaPixelsFromTop - 250) )
    :> //Insert swap logic from above
});
Zmart
  • 1,084
  • 8
  • 16