jimmy
jimmy

Reputation: 35

Detecting the position of a div and firing a function

im trying to fire a function when a div reaches a certain level in the scroll.

Could someone help me out with this?

Code / fiddle:

http://jsfiddle.net/6hJeT/5/

Upvotes: 1

Views: 106

Answers (5)

Shadow Wizard
Shadow Wizard

Reputation: 66389

Here you go: http://jsfiddle.net/6hJeT/21/

The trick is checking the scrollTop of the body (which means how much user has scrolled down) and compare it to the top position of your bottom div.

$(window).scroll(function () {
    if ((document.body.scrollTop +  + $("#shape").height()) >= $("#bottom-div").position().top)
        alert("Boo");
});

Upvotes: 0

Litek
Litek

Reputation: 4888

Using window.scrollTop() will get you there.

Alterntively, for more complicated cases you may want to look at jquery waypoints plugin.

Upvotes: 1

Joseph Marikle
Joseph Marikle

Reputation: 78520

http://fiddle.jshell.net/6hJeT/20/

looks like about the same answer as Nicola

Upvotes: 1

Billy Moon
Billy Moon

Reputation: 58531

You could:

if($('#shape').offset().top >= $('#top-div').height()) alert("Boo");

Upvotes: 0

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76880

You could do:

$(window).scroll(function(e) {
    var shape = $('#shape').position();
    var bottomDiv = $('#bottom-div').position();
    if (shape.top > bottomDiv.top){
        alert('passed');  
    }

});

fiddle here: http://jsfiddle.net/nicolapeluchetti/6hJeT/11/

Upvotes: 1

Related Questions