JimmyBanks
JimmyBanks

Reputation: 4698

Run a jQuery function when an element is viewed

Currently i have a load more button running when an element is clicked, as can be seen here:

<script type="text/javascript">
     $(document).on('click', '#loadmore', function() {

         etc....
     });
</script>

but is there a way to make this run when a div comes into the view of the browser? really turning it into an infinite load? I've been searching around and cant find any solutions, but it seems like something that is likely possible.

So a user will be browsing down the page, views element <div id="#loadmore"> and the function runs?

Upvotes: 0

Views: 303

Answers (4)

d4rkpr1nc3
d4rkpr1nc3

Reputation: 1827

if(window.addEventListener)
{
window.addEventListener("scroll", function() {
          var div = document.getElementById("myDiv");
          if(div.offsetTop <= window.innerHeight)
          {
               clearInterval(timer);
               // call your functions here
          });
}
else if(window.attachEvent)
{
     window.attachEvent("onscroll", function() {
          var div = document.getElementById("myDiv");
          if(div.offsetTop <= window.innerHeight)
          {
               clearInterval(timer);
               // call your functions here
          })
}

Upvotes: 0

devsnd
devsnd

Reputation: 7722

you can also use the following method, even though i would recommend using the library version suggested by xdazz

//returns the size of the whole html
function getDocHeight() {
    var D = document;
    return Math.max(
        Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
        Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
        Math.max(D.body.clientHeight, D.documentElement.clientHeight)
    );
}

//returns the size of the browser window
function viewport() {
    var e = window, a = 'inner';
    if ( !( 'innerWidth' in window ) ){
        a = 'client';
        e = document.documentElement || document.body;
    }
    return { width : e[ a+'Width' ] , height : e[ a+'Height' ] }
}

//register a scroll listener, that checks if you are at the end of the page
$(window).scroll(function(){
    if( $(window).scrollTop()+viewport()["height"] >= getDocHeight() ){
         //your method here
         loadMore();
    }
});

Upvotes: 2

RTulley
RTulley

Reputation: 175

http://api.jquery.com/visible-selector/

The jquery visible selector will work

Upvotes: -2

xdazz
xdazz

Reputation: 160833

You could try this plugin jquery-appear.

Upvotes: 3

Related Questions