Fire event when div is visible to visitor with jQuery?

前端 未结 4 1009
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-01 04:08

The function: I want to change the class of a certain item when a user see a certain div (scrolls down to it).

How I do it now: I\'

相关标签:
4条回答
  • 2021-01-01 04:19

    This would probably be useful for you.

    Anyhow, you could probably do it without a plug-in and with a simple expression instead:

    var elem_top    = $("some_element").offset().top;
    var elem_height = $("some_element").height();
    var wind_height = $(window).height();
    var scrollTop   = $(window).scrollTop;
    
    if (elem_top > (wind_height + scrollTop) &&
       !(elem_top + elem_height) < wind_scrollTop) 
    {
        //The element is inside the screen (e.g. it is directly visible)
    }
    
    0 讨论(0)
  • 2021-01-01 04:25

    By looking at the source code of the jquery-appear plugin, it is possible to pass the argument one, to fire the event one time only (one: true), or every time it appears (one: false)

    $('#myDiv').appear(function() {
        $("#aDiv").addClass("active");
    }, {
        one: false
    });
    
    0 讨论(0)
  • 2021-01-01 04:28

    I use a similar plugin but this uses the bind method and uses an event -> http://remysharp.com/2009/01/26/element-in-view-event-plugin/

    Sample usage :

    $('div').bind('inview', function (event, visible) {
      if (visible == true) {
        // element is now visible in the viewport
      } else {
        // element has gone out of viewport
      }
    });
    
    0 讨论(0)
  • 2021-01-01 04:42

    to judge the div is visible or not, you can:

    $(window).scroll(function(event) {
        console.log($(".target").offset().top < $(window).scrollTop() + $(window).outerHeight());
    });
    

    so, i don't think you need any plugin.

    just judge it by the expression like:

    if($(".target").offset().top < $(window).scrollTop() + $(window).outerHeight()) {
        // something when the .target div visible
    } else {
        // something when the .target div invisible
    }
    
    0 讨论(0)
提交回复
热议问题