1

I have looked for other answers on the same topic but still cannot find a solution why the event is firing more times in my code:

  (function($, Drupal, drupalSettings) {
    Drupal.behaviors.news = {
        'attach': function(context) {

            $(".loader").hide();
            var loadIndex = 0;
            var isLoading = false;

            $(window).scroll(function(){
                if (!isLoading) {
                    var footerHight = $(document).height() - $(window).height() - $("#myFooter").height();
                    if($(window).scrollTop() > footerHight){

                        isLoading = true;
                        loadIndex = loadIndex + 1;

                        $(".loader").show();
                        $.ajax({
                            method: "GET",
                            url: '/load-news?startIndex=' + loadIndex,
                            success: function (result) {
                                console.log("More loaded");
                                setTimeout(function(){
                                    $(".loader").hide();
                                    onSuccess(result);
                                    isLoading = false;
                                }, 1000);

                            }
                        });
                    }
                }
            })
        }
    };

    var onSuccess = function(data) {
        console.log('SUCCESS');
        $(".news-list-wrapper").append(data);
    };

})(jQuery, Drupal, drupalSettings);

1 Answer 1

3

When using Drupal.behaviors you need to use .once('behaviorName')

$(window).scroll(function(){

needs to be:

$(window, context).once('news').scroll(function(){
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.