JavaScriptプログラムに関する各種メモ書き

jQueryで "ある要素" が画面内にあるかどうかを判別する

jQueryで "ある要素"が画面内にあるかどうかを判別するには 要素のページ内での位置( Y座標)、 現在のスクロール位置( Y座標)、 要素の高さを見て判別します。

function is_in_sight(jq_obj) {
	var scroll_top    = $(window).scroll_top();
	var scroll_bottom = scroll_top + $(window).height();
	var target_top    = jq_obj.offset().top;
	var target_bottom = target_top + jq_obj.height();
    if (scroll_bottom > target_top && scroll_top < target_bottom) {
    	alert('in sight');
    } else {
    	alert('not in sight');
    }
}

$(function() {
    $(window).on('load scroll', function() {
        is_in_sight($('.my-class'));
    });
});

関連エントリー

No.879
09/05 12:27

edit

jQuery