Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery trigger function when element is in viewport

I'd like to trigger an event when jquery.localscroll reaches a certain point of the document, a div.

Lets say we're scrolling vertically from the top div to the third. When it gets there, then the action schould trigger.

like image 798
Aeonius Avatar asked May 06 '11 12:05

Aeonius


2 Answers

jQuery Waypoints plugin http://imakewebthings.github.com/jquery-waypoints/ should do the trick

UPDATE

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>jQuery Waypoints Plugin - Test</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js" type="text/javascript"></script>
    <script src="http://imakewebthings.github.com/jquery-waypoints/waypoints.min.js" type="text/javascript"></script>
    <style type="text/css">
        #mydiv {background-color:#FF0000; margin:1500px 0;}
    </style>
</head>
<body>

<div id="mydiv">
    Content goes here
</div>

<script type="text/javascript">
$(function() {
       $('#mydiv').waypoint(function() {
         window.location.href = 'http://google.com';
         }, {
           offset: '100%'
         });
    });
</script>
</body>
</html>
like image 109
Pav Avatar answered Nov 03 '22 04:11

Pav


You may want to also see the following tiny plugin, it's help me in the past and it's pretty clean:

  • http://remysharp.com/2009/01/26/element-in-view-event-plugin/

Example Usage:

$('div').bind('inview', monitor);
function monitor(event, visible)
{
    if(visible)
    {
      // element is now visible in the viewport
    }
    else
    {
      // element has gone out of the viewport
    }
}
like image 19
RobertPitt Avatar answered Nov 03 '22 04:11

RobertPitt