Search code examples
jqueryscrollgoogle-dfp

How to inject once when using $(window).scroll?


I would like to run "window.googletag.pubads().refresh();" once when an user scrolls > 2000px. How do I do it properly? As an example:

    $(window).scroll(function() {
    var st = $(this).scrollTop();
    var lastScrollTop = 2000;

    if (st > lastScrollTop) {
        window.googletag.pubads().refresh();
        console.log('refresh');
    }
});

Solution

  • I don't think adding a boolean data type named flag is very comprehensive, especially when the OP doesn't appear to understand the need for a bool. It doesn't tell him what he needs to get this done. The above answer is correct, but it may not be comprehensive to people googling this question in the future, and they may not understand what you mean by "flag."

    Not knowing when to use a boolean data type is a symptom of a much larger prolem here that should be explained, so the OP doesn't continue in ignorance.

    What you need is a boolean variable. Essentially, you want to check if something is true or not. Did we scroll to the position already? No, so let's trigger it. Did we already do that? Then it won't scroll again until the page is refreshed.

    Let's create the bool: var scrolledToPosition = false;. This must be placed outside of the scroll logic, or it will be reset every single time, and it won't work.

    You want it to be set to false initially, so the upcoming additional logic will fire correctly.

    Then, in your if statement, if (st > lastScrollTop), you'll want to add && !scrolledToPosition.

    The exclamation point means "not." For example, if bool scrolledToPosition equals false, you can check this by using !booleanValue. You can exclude the exclamation point to check if it's true. For example, if (scrolledToPosition).

    Here's the full code:

    var scrolledToPosition = false;
    var lastScrollTop = 2000;
    
    $(window).scroll(function() {
        var st = $(this).scrollTop(); 
    
        if (st > lastScrollTop && !scrolledToPosition) {
            window.googletag.pubads().refresh();
            console.log('refresh');
            scrolledToPosition = true;
        }
    });
    

    If you ever need to reset that, just set scrolledToPosition to false. Like this:

    scrolledToPosition = false;