Run jQuery event only once after a condition matches

前端 未结 5 1420
温柔的废话
温柔的废话 2021-01-06 05:54

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 onl

相关标签:
5条回答
  • 2021-01-06 06:01

    you can unbind the event after complete.

    Like $(this).unbind("scroll);

    0 讨论(0)
  • 2021-01-06 06:12

    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");
    });
    
    0 讨论(0)
  • 2021-01-06 06:13

    I think what you need is .one method

    $(window).one("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");
        }       
    });
    

    You can learn more here: http://api.jquery.com/one/

    0 讨论(0)
  • 2021-01-06 06:21

    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);
        }
    };
    
    0 讨论(0)
  • 2021-01-06 06:26
    var thisHash = window.location.hash;
    jQuery(document).ready(function() {
    
        if(window.location.hash) {
          jQuery.fancybox(thisHash, {
            padding: 20
            // more API options
          });
        }
    
    });
    

    This is even better, because you don't need the button to trigger fancybox. And with the previous code I wasn't able to insert a form inside fancybox, cause everytime I was clicking inside the form, it was relaunching fancybox.

    0 讨论(0)
提交回复
热议问题