Test in JQuery if an element is at the top of screen
I have a div
that is positioned about 100px from the top of the browser window. When the user scrolls down, I want the div
to stay where it is until it reaches the top of the screen. Then, I'll change some CSS w开发者_JS百科ith JQuery to make the position to change to fixed and the margin-top to 0. How can I test in JQuery if this div
is at the top of the screen?
var distance = $('div').offset().top,
$window = $(window);
$window.scroll(function() {
if ( $window.scrollTop() >= distance ) {
// Your div has reached the top
}
});
P.S. For better performance, you should probably throttle the scroll event handler.
Check out John Resig's article: Learning from Twitter.
hey you can do like this :
var distance = $('.yourclass').offset().top;
$(window).scroll(function() {
if ( $(this).scrollTop() >= distance ) {
console.log('is in top');
} else {
console.log('is not in top');
}
});
Not so much an answer, but could be helpful to someone else. Using the accepted answer above and also referencing the 'Learning from Twitter' link (thank you @Joseph Sibler) I came up with the following.
I am using a Twitter Bootstrap Navbar for my primary navigation. It has an ID of megamenu
.
I also have a 'login' button on my page that when clicked, slides the navbar and all contents below it down to reveal the login form. So what? Well, now the position of my navbar has changed and if I don't update that position, when I scroll the navbar will fly up to the top of the browser - even though it's not really at the top.
I came up with this to update the navbar position so if a user clicks 'login' and then scrolls, the navbar will correctly fix itself to the top.
logincollapse
is my container div that holds the login form and other hidden content until the login
button is clicked.
I'm sure there is room for improvement - so please correct me, I'll update accordingly.
jquery
var did_scroll = false,
$window = $(window),
megamenu_distance = $('#megamenu').offset().top; // The default position of the navbar
$('#logincollapse').slideToggle(300, 'easeInOutQuint', function () {
megamenu_distance = $('#megamenu').position().top; // Updated position of the navbar
....
});
$window.scroll(function (event) {
did_scroll = true;
});
setInterval(function () {
if (did_scroll)
{
did_scroll = false;
if ($window.scrollTop() >= megamenu_distance)
{
$('#megamenu').addClass('navbar-fixed-top');
}
else
{
$('#megamenu').removeClass('navbar-fixed-top');
}
}
}, 250);
when you have header. and then aside bar. for fixing aside bar, when it is at top of the screen:
Javascript:
var scroll_happened = false;
var aside_from_top = $('aside').offset().top;
$window = $(window);
$window.scroll(function()
{
scroll_happened = true;
});
setInterval(function()
{
if(scroll_happened == true)
{
scroll_happened = false;
if($window.scrollTop() >= aside_from_top)
{
$('#aside_container').addClass('fixed_aside');
}
else
{
$('#aside_container').removeClass('fixed_aside');
}
}
} , 250);
Css:
.fixed_aside
{
position: fixed;
top: 0;
bottom: 0;
}
Html:
<aside>
<div id="aside_container">
<section>
</section>
<section>
</section>
<section>
</section>
</div>
</aside>
$(document).ready(function(){
var $doc = $(document);
var position = 0;
var top = $doc.scrollTop(); // 현재 스크롤바 위치
var screenSize = 0; // 화면크기
var halfScreenSize = 0; // 화면의 반
/* 사용자 설정 값 시작 */
var pageWidth = 1000; // 페이지 폭, 단위:px
var leftOffet = 409; // 중앙에서의 폭(왼쪽 -, 오른쪽 +), 단위:px
var leftMargin = 909; // 페이지 폭보다 화면이 작을때 옵셋, 단위:px, leftOffet과 pageWidth의 반만큼 차이가 난다.
var speed = 1500; // 따라다닐 속도 : "slow", "normal", or "fast" or numeric(단위:msec)
var easing = 'swing'; // 따라다니는 방법 기본 두가지 linear, swing
var $layer = $('#quick'); // 레이어 셀렉팅
var layerTopOffset = 140; // 레이어 높이 상한선, 단위:px
$layer.css('z-index', 10); // 레이어 z-인덱스
/* 사용자 설정 값 끝 */
// 좌우 값을 설정하기 위한 함수
function resetXPosition()
{
$screenSize = $('#contact').width(); // 화면크기
halfScreenSize = $screenSize / 2; // 화면의 반
xPosition = halfScreenSize + leftOffet;
if ($screenSize < pageWidth)
xPosition = leftMargin;
$layer.css('left', xPosition);
}
// 스크롤 바를 내린 상태에서 리프레시 했을 경우를 위해
if (top > 0 )
$doc.scrollTop(layerTopOffset+top);
else
$doc.scrollTop(0);
// 최초 레이어가 있을 자리 세팅
$layer.css('top',layerTopOffset);
resetXPosition();
// 윈도우 크기 변경 이벤트가 발생하면
$(window).resize(resetXPosition);
// 스크롤이벤트가 발생하면
$(window).scroll(function(){
yPosition = $doc.scrollTop() + layerTopOffset;
$layer.animate({"top":yPosition }, {duration:speed, easing:easing, queue:false});
});
});
精彩评论