Steffi
Steffi

Reputation: 7087

How to do something when user scroll until a div?

I have a div id="content".

Is it possible to do an action if a user see the id="content" ?

Upvotes: 3

Views: 4110

Answers (5)

no.good.at.coding
no.good.at.coding

Reputation: 20371

You could use .scrollTop() perhaps. Something like:

function scrolledTo(el, shownCallback, hiddenCallback) {
    var isVisible = false;
    var isScrolledTo = function(){
       var docViewTop = $(window).scrollTop();
        var docViewBottom = docViewTop + $(window).height();

        var elemTop = $(el).offset().top;
        var elemBottom = elemTop + $(el).height();

        return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
    }

    $(window).scroll(function(){
        if(isScrolledTo()){
            if(!isVisible){
                isVisible = true;
                if(shownCallback)(shownCallback());
            }
        } else {
            if(isVisible){
                isVisible = false;
                if(hiddenCallback)(hiddenCallback());
            }
        }
    });
}

Contains code from Check if element is visible after scrolling

Here's a fiddle.

Upvotes: 1

ChrisThompson
ChrisThompson

Reputation: 2008

you can check to see if the top of the div is within the window view. This code would need enhanced in case you went below the div.

    $(document).ready(function(){
    var divTop = $('#test5').get(0).offsetTop;

    $(window).scroll(function(){
        var windowHeight = $(window).height();
        var top = $(window).scrollTop();
        var windowBottom = (top+windowHeight);
        if(windowBottom > divTop){
            console.log('div in view');
        }
    });
});

HTML:

    <div id="test1" style="display: block; height: 200px;">1</div>
<div id="test2" style="display: block; height: 200px;">2</div>
<div id="test3" style="display: block; height: 200px;">3</div>
<div id="test4" style="display: block; height: 200px;">4</div>
<div id="test5" style="display: block; height: 200px;">5</div>

Upvotes: 0

Hussein
Hussein

Reputation: 42818

I answered a similar questions at horizontal scroll, detecting scroll position relative to anchors

See working example http://jsfiddle.net/Vy33z/4/

You can also use a plugin if you are not too familiar with jQuery. The Appear plugin is great and easy to use. All you need to do is

$('#mydiv').appear(function() {
  alert('Your div is in view');
});

Upvotes: 5

Damb
Damb

Reputation: 14610

You can do it easily with this jQuery plugin: jQuery Waypoints

Upvotes: 2

Mottie
Mottie

Reputation: 86483

See, as inside the browser viewport? Have you looked at this viewport selector plugin?

Upvotes: 2

Related Questions