16

I noticed that jquery scroll event automatically triggered when some content push at the top of the page by ajax. Any expert know how to avoid scroll event being triggered when the content has been added? But scroll event triggered when user run the mousewheel, page up down as well as keyboard up and down probably?

$(window).on('scroll', function () {
        console.log("User manual scrolled.");
    });

Based on this example. https://jsfiddle.net/q00jnv4n/

Su Beng Keong
  • 1,034
  • 1
  • 13
  • 30

5 Answers5

3

.off function used to Remove an event handler.

You should be using $(window).off("scroll") just before loading content by ajax and then again use $(window).on('scroll', function () { after loading the content

By using .off your scroll handler will be remove while content is being loaded on site.

Vikram
  • 3,171
  • 7
  • 37
  • 67
0

One option to stop the display appearing to move is to adjust the scrollTop by the amount the #result div has changed in height e.g. scrollTop = (scrollTop + newHeight - oldHeight):

function AddContent() {
    var height = $('#result').height();
    console.log("height: " + height);
    $(".UnloadedPara").each(function () {
        //console.log();
        $(this).replaceWith("<div>This is some new paragraph</div>");
    });

    var newHeight = $('#result').height();
    $(window).scrollTop($(window).scrollTop() + newHeight - height);
}

JSFiddle: https://jsfiddle.net/TrueBlueAussie/q00jnv4n/12/

iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202
0

You are using window.scrollTop() in your code. It will automatically trigger scroll event in jQuery as jQuery uses window.scrollTo() under the hood.

You cannot suppress 'scroll' event fired by this. But you can use a hack to detect if scroll event was called after you 'AddContent' called window.scrollTop(). You can do it by setting a boolean variable in your AddContent to false. And check in your scroll event handler if the variable if false or not. If it is false then set it to true and don't do anything. Otherwise perform you desired action.

I forked your jsfiddle and updated it: JsFiddle

Shoaib Shakeel
  • 1,447
  • 18
  • 24
0

referring to this post, there exists an event only listening to mousescroll.

$(window).bind('mousewheel DOMMouseScroll', function(e){
    if (e.originalEvent.wheelDelta > 0 || e.originalEvent.detail < 0) {
        // scroll up
    } else {
        // scroll down
    }
});

greetings timotheus

Community
  • 1
  • 1
Timotheus0106
  • 1,536
  • 3
  • 18
  • 28
0

This is merely a workaround, but if you need a quick fix you can have the window scroll back to the button after the new content has been loaded at the top.
https://jsfiddle.net/msfq5mx0/

$(window).scrollTo(0,$("#btnAddContent").offset().top);
Mike Hamilton
  • 1,519
  • 16
  • 24