3

I have a div id="content".

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

Kara
  • 6,115
  • 16
  • 50
  • 57
Steffi
  • 6,835
  • 25
  • 78
  • 123

5 Answers5

5

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');
});
Community
  • 1
  • 1
Hussein
  • 42,480
  • 25
  • 113
  • 143
2

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

Mottie
  • 84,355
  • 30
  • 126
  • 241
  • Maybe, but I don't wanna use plugin – Steffi Apr 07 '11 at 20:01
  • 1
    Why not use a plugin? That plugin is actually very small, you could just copy and paste its code into the page header. Or just look at it's source and take what you need. – Mottie Apr 07 '11 at 20:05
2

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

Damb
  • 14,410
  • 6
  • 47
  • 49
1

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.

Community
  • 1
  • 1
no.good.at.coding
  • 20,221
  • 2
  • 60
  • 51
0

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>
ChrisThompson
  • 1,998
  • 12
  • 17