Josh
Josh

Reputation: 153

jQuery Scroll event firing without actually scrolling

My website has pages that dynamically load content without having to change pages. I have the following jquery plugin created in my javascript file which should do certain things when the page is scrolled to the bottom.

$.fn.scrollEvent= function() {
    $(document).on("scroll", function() {
        console.log("Scroll");
        if($(window).scrollTop() + $(window).height() == $(document).height()) {
            // do stuff
        }
    });
};

So when a menu item is clicked, I load the new page content and I call the jquery plugin so it can be used on the new page.

$(document).ready(function() {
    $(document).on("click", ".menu-item", function() {
        $.fn.scrollEvent();
        // do other page stuff
    });
});

However, what i'm noticing is that when I call the plugin, the console is logging "Scroll" before I do anything on the page. So the scrolling event is being called once or even twice without me actually scrolling at all.

Why this is this happening? Is there a better way to do this?

Upvotes: 3

Views: 1292

Answers (1)

A. Wolff
A. Wolff

Reputation: 74420

You should use following pattern:

$.fn.scrollEvent = function () {
    return this.on("scroll", function () {
        console.log("Scroll");
        if ($(window).scrollTop() + $(window).height() == $(document).height()) {
            // do stuff
        }
    });
};

$(window).scrollEvent(); //bind event to windwo or any element

Upvotes: 1

Related Questions