jquery.inview

A jQuery plugin that adds a bindable 'inview' event for detecting when an element is scrolled into view.

  • 所有者: protonet/jquery.inview
  • 平台:
  • 許可證: Do What The F*ck You Want To Public License
  • 分類:
  • 主題:
  • 喜歡:
    0
      比較:

Github星跟蹤圖

Element 'inview' Event Plugin

Event that is fired as soon as an element appears in the user's viewport.

Usage

The script makes use of the new $.contains method - so it will only work with jQuery 1.8 upwards. If you need to use it with older versions of jQuery, drop a comment, and I'll post an alternative.

The event will only fire when the element comes in to view of the viewport, and out of view. It won't keep firing if the user scrolls and the element remains in view.

The variable after the event argument indicates the visible state in the viewport.

$('div').on('inview', function(event, isInView) {
  if (isInView) {
    // element is now visible in the viewport
  } else {
    // element has gone out of viewport
  }
});

To stop listening for the event - simply unbind:

$('div').off('inview');

If you would like the event only to trigger once per element while the page is loaded, you can use the .one() method instead of .on():

$('div').one('inview', ...);

Live events

Yep, inview events can also be used with .on/.delegate methods.
Please note that this could slow down your app when the selector is too complex and/or matches a huge set of elements.
The following code snippet only loads images when they appear in the browser's viewport.

// Assuming that all images have set the 'data-src' attribute instead of the 'src'attribute
$("body").on("inview", "img[data-src]", function() {
  var $this = $(this);
  $this.attr("src", $this.attr("data-src"));
  // Remove it from the set of matching elements in order to avoid that the handler gets re-executed
  $this.removeAttr("data-src");
});

Use cases

  • Reduce http requests and traffic on server by loading assets (images, javascript, html, ...) only when they are visible to the user
  • Endless scrolling (twitter-like)
  • Tracking (eg. to see whether a user has read an entire article)
  • ...

Browser Compatibility

The Test Suite succeeds in the following browsers that were tested:

  • Firefox 3+
  • Safari 3+
  • Chrome 7+
  • Opera 10+
  • IE 6+
  • Mobile Safari on iPad 4.2.2

主要指標

概覽
名稱與所有者protonet/jquery.inview
主編程語言HTML
編程語言JavaScript (語言數: 2)
平台
許可證Do What The F*ck You Want To Public License
所有者活动
創建於2010-11-22 18:50:35
推送於2021-06-05 07:38:49
最后一次提交2017-07-29 18:09:24
發布數4
最新版本名稱v1.1.2 (發布於 2016-01-26 16:52:54)
第一版名稱v1.0.0 (發布於 2014-03-15 15:03:02)
用户参与
星數1.7k
關注者數85
派生數482
提交數94
已啟用問題?
問題數56
打開的問題數33
拉請求數8
打開的拉請求數8
關閉的拉請求數12
项目设置
已啟用Wiki?
已存檔?
是復刻?
已鎖定?
是鏡像?
是私有?