Kiran T
Kiran T

Reputation: 1

Triggering button click on scroll triggers multiple clicks

I am trying to trigger button click on scroll when the scroller hits the div. below is the code which i tried but when the scroller hits the div it is triggering multiple clicks and loading next multiple set of data. Can anyone suggest me how to trigger click only once.

Thanks for the help in advance :)

$(window).scroll(function() {
    var divTop = $('.hit-scroll').offset().top,
    divHeight = $('.hit-scroll').outerHeight(),
    wHeight = $(window).height(),
    windowScrTp = $(this).scrollTop();
    if (windowScrTp > (divTop+divHeight-wHeight)){
        $('body').find('.show-more button').trigger('click');
    }
}); 

Note: on button click an ajax call is made which loads next set of data.

Upvotes: 0

Views: 558

Answers (2)

Kiran T
Kiran T

Reputation: 1

i found this solution more precise and working great..

function bindScroll(){
var divTop = $('.hit-scroll').offset().top,
divHeight = $('.hit-scroll').outerHeight(),
wHeight = $(window).height(),
windowScrTp = $(this).scrollTop();
if (windowScrTp > (divTop+divHeight-wHeight)){
       $(window).unbind('scroll');
       $('body').find('.show-more button').trigger('click');
}

}

$(window).scroll(bindScroll);

Upvotes: 0

Problem is that everytime you scroll down 1px you run the $(window).scroll

So imagine that windowScrTp > (divTop+divHeight-wHeight) is equal to 200 > (168) that means your click function would be triggered twice.

I surgess you make a variable load like the example below, that should stop it from loading multiple times.

var load = true;
$(window).scroll(function() {
    var divTop = $('.hit-scroll').offset().top,
    divHeight = $('.hit-scroll').outerHeight(),
    wHeight = $(window).height(),
    windowScrTp = $(this).scrollTop();
    if (windowScrTp > (divTop+divHeight-wHeight)){
        if(load){
          load = false;
          $('body').find('.show-more button').trigger('click');
        }
    }
});

Inside your ajax success call I would add load = true;

I've created a demo than shows the idea below.

Demo

var load = true;
$(window).scroll(function() {
  var windowScrTp = $(this).scrollTop();
  if (windowScrTp > (200)) {
    if (load) {
      console.log("load start")
      load = false;
      $('body').find('.show-more button').trigger('click');
    }
  }
});

$('.show-more button').click(function() {
  setTimeout(
    function() {
      console.log("load stop")
      load = true;
    }, 2000);
});
body {
  height: 2000px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="show-more"><button>more</button></div>

Upvotes: 2

Related Questions