Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run jQuery event only once after a condition matches

Tags:

html

jquery

I am making online product site, I am trigging a scroll event, at starting only 12 elements will be shown but when 8th element is scrolled to top scroll event should run only once, but it is running every time when I scroll down, please help. Here is my Code:

var navigation_offset_top = $('.prods-list li:nth-child(4)').offset().top;  
    $(window).on("scroll",function(){
        var scroll_top = $(window).scrollTop(); // current vertical position from the top
        // if scrolled more than the navigation, change its position to fixed to stick to top, otherwise change it back to relative
        if (scroll_top > sticky_navigation_offset_top) 
        { 
            console.log("Hi");
        }       
    });
like image 599
Bharat Soni Avatar asked Dec 11 '22 16:12

Bharat Soni


2 Answers

Use on() and off(), and unbind the event handler when the scrolling reaches the right point :

var navigation_offset_top = $('.prods-list li:nth-child(4)').offset().top;  

$(window).on("scroll", doScroll);

function doScroll() {
    var scroll_top = $(window).scrollTop();
    if (scroll_top > sticky_navigation_offset_top) { 
        console.log("Hi");
        $(window).off('scroll', doScroll);
    }
};
like image 143
adeneo Avatar answered Jan 05 '23 04:01

adeneo


Call unbind() to unbind the event from the object.

$(window).on("scroll",function(){
    var scroll_top = $(window).scrollTop(); // current vertical position from the top
    // if scrolled more than the navigation, change its position to fixed to stick to top, otherwise change it back to relative
    if (scroll_top > sticky_navigation_offset_top) 
    { 
        console.log("Hi");
    }       
    $(this).unbind("scroll");
});
like image 42
Daniel Imms Avatar answered Jan 05 '23 03:01

Daniel Imms