[JS]jQueryのプラグインを利用する時に、アイデアを加えてかっこいいエフェクトを実装する -jQuery Visible
Post on:2013年3月29日
sponsorsr
シンプルな機能のjQueryのプラグインを利用して、スクロールして次のコンテンツを表示する時にかっこいいエフェクトを与えるテクニックを紹介します。

Slide In (as you scroll down) Boxes
使用プラグイン:jQuery Visible
まずは、使用するプラグインからご紹介。

jQuery Visible
jQuery Visible -GitHub
jQuery Visibleは、ページ上の要素がビューポート内にあるかどうかチェックするプラグインです。
デモページでその動作が確認できます。
右のボタン「Detect Visibility」をクリックします。

ビューポート内に配置されている要素にはグリーンの「Onscreen」
スクロールして、ビューポート内に配置されていなかった要素を表示します。

ビューポート外の見えてなかった要素にはイエローの「Offscreen」
jQuery Visibleを使ったナイスアイデア
このjQuery Visibleのビューポート内に要素があるかどうかチェックする機能を使ったナイスアイデアのデモを紹介します。

スクロールをしてビューポート外の要素を表示する時、スクロールに追従するようなアニメーションで次の要素を表示します。
このエフェクトは、Nexus7でGoogle+アプリをスクロールダウンした時のような感じです。
実装
使用するプラグイン「jQuery Visible」は、非常にシンプルです。
(function($){
/**
* Copyright 2012, Digital Fusion
* Licensed under the MIT license.
* http://teamdf.com/jquery-plugins/license/
*
* @author Sam Sehnert
* @desc A small plugin that checks whether elements are within
* the user visible viewport of a web browser.
* only accounts for vertical position, not horizontal.
*/
$.fn.visible = function(partial){
var $t = $(this),
$w = $(window),
viewTop = $w.scrollTop(),
viewBottom = viewTop + $w.height(),
_top = $t.offset().top,
_bottom = _top + $t.height(),
compareTop = partial === true ? _bottom : _top,
compareBottom = partial === true ? _top : _bottom;
return ((compareBottom <= viewBottom) && (compareTop >= viewTop));
};
})(jQuery);
ウインドウのスクロール時に表示される要素に、classを付与します。
$(window).scroll(function(event) {
$(".module").each(function(i, el) {
var el = $(el);
if (el.visible(true)) {
el.addClass("come-in");
}
});
});
スライドのアニメーションは、CSS3です。
.come-in {
transform: translateY(150px);
animation: come-in 0.8s ease forwards;
}
.come-in:nth-child(odd) {
animation-duration: 0.6s; /* So they look staggered */
}
@keyframes come-in {
to { transform: translateY(0); }
}
要素が既に表示なのか、スクロールで表示されるのかをチェックし、classを付与します。
var win = $(window);
var allMods = $(".module");
// Already visible modules
allMods.each(function(i, el) {
var el = $(el);
if (el.visible(true)) {
el.addClass("already-visible");
}
});
win.scroll(function(event) {
allMods.each(function(i, el) {
var el = $(el);
if (el.visible(true)) {
el.addClass("come-in");
}
});
});
sponsors











