How to detect which element is on the center of the screen with scroll position?

2.7k views Asked by At

I want to detect which element is visible on the screen when scrolling down/up. I have to set as active menu item on the menu which targets that element.

// must have a page class
$('.page').each(function(){
    $positionData[$(this).attr('id')] = $(this).offset().top;
});

$(document).scroll(function(){
    var $position = $(this).scrollTop();
    if($position > $height && !$body.hasClass('scrolled')) {
        $body.addClass('scrolled');

        //detech the scroll is between an element offset
    } else if($position < $height) {
        $body.removeClass('scrolled');
    }
});

Any idea?

2

There are 2 answers

1
Canser Yanbakan On BEST ANSWER

For Bootstrap users;

There is a component already can be found named Scrollspy.

Scrollspy

How to use?

1: Add relative positioning to body.

body {
    position: relative;
}

2: Add data-spy="scroll" and data-target="" attributes to your body. (data-target must target your menu)

<body data-spy="scroll" data-target="#navbar-example">

3: Set your menu. Don't for get to add nav class to your ul/ol element.

<div id="navbar-example">
    <ul class="nav">
        <li><a href="#home">HOME</a></li>
        <li><a href="#project">PROJECT</a></li>
    </ul>
</div>

4: Check your target elements to every element must have an id attribute same as your link targets.

<div id="home"></div>
2
North On

You can use jquery plugin inview (github) to do that.

$('.scrollWatch').bind('inview', function (event, visible) {
    if (visible) {
        // do something here
        $(this).addClass('scrolled');
        $(this).text('mom! I\'m here.');
    } else {
        // do something here with invisible
        $(this).removeClass('scrolled');
        $(this).text('1');
    }
});

I created a demo jsfiddle for you, please use DevTools to see what changes in HTML.