user4973992
user4973992

Reputation:

How to use jQuery .one with .scroll?

I want this ajax to load only when there's a scroll event, but only one time (instead of every time the user scrolls.

$(window).scroll(function(){
    $.ajax({
      url: "/reviews"
    })
      .done(function( html ) {
        $( "#reviews-ajax" ).append(html);
      });
 }); 

Upvotes: 0

Views: 724

Answers (2)

adeneo
adeneo

Reputation: 318302

You can use jQuery's one()

$(window).one('scroll', function(){
    $.ajax({
      url: "/reviews"
    }).done(function( html ) {
        $( "#reviews-ajax" ).append(html);
    });
}); 

one()

Attach a handler to an event for the elements. The handler is executed at most once per element per event type.

Upvotes: 3

Himanshu Upadhyay
Himanshu Upadhyay

Reputation: 6565

Use a flag like this:

$(document).ready(function(){
    var flag = 0;
    $(window).scroll(function(){
        if(flag == 0){
            flag = 1;
            $.ajax({
               url: "/reviews"
            })
           .done(function( html ) {
              $( "#reviews-ajax" ).append(html);
            });
        }
     }); 
});

Upvotes: 0

Related Questions