Frank Aguilar
Frank Aguilar

Reputation: 251

Triggering Jquery at certain length of page

I'm trying to figure how to trigger an jquery animation when the user scrolls to the middle of the page. Is there a way to set a listener to see if the person scrolls halfway down the page it activates the jquery code?

Upvotes: 1

Views: 260

Answers (3)

saluce
saluce

Reputation: 13360

Using jQuery, you can attach an event handler to the scroll event, which will let you listen to whenever the window is scrolled and determine whether the user has scrolled the appropriate amount.

$(window).scroll(function () { 
    if (($(window).scrollTop()) > ($(document).height() / 2)) {
        // Run animation here
    }
});

http://jsfiddle.net/ult_combo/XdqPJ/1/

Upvotes: 1

Alex W
Alex W

Reputation: 38253

Is there a way to set a listener to see if the person scrolls halfway down the page it activates the jquery code?

You can get the amount that the user has scrolled with the following:

$("html,body").scrollTop();

so, to trigger an event halfway down the page:

if (($("html,body").scrollTop()) > ($("html,body").height() / 2))
{
    // Code that will be triggered
}

You would need a timer to constantly be checking this. You can use setInterval() in Javascript to repeatedly execute a function to check this.

http://api.jquery.com/scrollTop/

Upvotes: 0

Raiden
Raiden

Reputation: 484

Think so.. you can look at checking parts of the page using; setInterval(name_Of_Function,1000);

runs every second, then run a check on there is; window.pageYOffset // Gives you current horizontal window scroll position for the page.

Firebug is helpful to get more information on these functions. Remember to check in all major browsers as the implementation or values returned may be slightly different between different browsers.

Good reference page I found; http://www.softcomplex.com/docs/get_window_size_and_scrollbar_position.html

Upvotes: 0

Related Questions