2

I have a structure like the following to create a one page web application, using some scroll functionalities:

<div class="home_section"></div> <!-- 1 -->
<div class="home_section"></div> <!-- 2 -->
<div class="home_section"></div> <!-- 3 -->
<div class="home_section"></div> <!-- 4 -->

I need to scroll to each of the above DIVs when the scroll event starts. So, for example, when the scroll starts, if the first DIV visible from top is <!-- 2 -->, the body will have to scroll to the DIV <!-- 3 --> automatically.

This is what I am doing:

if ($(this).attr('id') == 'home') {
    $(document).on("scrollstart", function (e) {
        console.log('scrolling started on home');

         e.preventDefault();

         var next = $(this).find(".home_section"); //here I need to calculate which is the next DIV to scroll to
         $('html, body').animate({
               scrollTop: next.offset().top
          });

    });
}

The problem is that I do not know how to check which is the first .home_section DIV visibile starting from top, so I am unable to calculate which is the next target DIV to scroll to.

Thanks for ay help

BeNdErR
  • 17,471
  • 21
  • 72
  • 103
Anonymous
  • 1,021
  • 2
  • 10
  • 24

3 Answers3

1

I would loop through all the .home_sections divs, and get the first :visible like this

var divs = $(".home_section");
for(var x = 0; x < divs.length; x++){
    if($(divs[x]).is(":visible")){
        //do what you need here 
        var me = divs[x];
        var next = x < divs.length - 1 ? divs[x] : undefined;
        if(next){
            //do the scroll
        }
        //then break the for loop
        break;
    }
}

This way you have an array of divs, you find the first visible and then you have the reference to the nth+1 div.

Another solution that should work:

var firstVisible = $(".home_section:visible:eq(0)");
var next = $(firstVisible).next();

hope this helps

BeNdErR
  • 17,471
  • 21
  • 72
  • 103
0

next div would be $(this).next();

var next = $(this).next();

But you would need to modify this line for it to work for all divs:

if ($(this).attr('id') == 'home')
Jure Špik
  • 331
  • 2
  • 11
-1

Modify the line var next = $(this).find(".home_section"); as below to get first div with class "home_section".

var next = $(this).getElementsByClassName("home_section")[0];

Madhura KM
  • 140
  • 1
  • 10
  • This is at least a very strange jQuery answer, if not invalid completely. getElementsByClassName is a vanilla method, not jQuery. – ArtOfCode Dec 01 '14 at 13:08