Reputation: 57
The Link to an Example: http://jsfiddle.net/j65yQ/
/* First: */
/* Set the Position of the Division Tag to Fixed When Reaching the Top of the Window While Scrolling */
$(window).scroll(function(){
var u_div_cn = $('div#container_nav');
var u_os_top_read = $('div#container_nav').offset().top;
if ($(window).scrollTop() > u_os_top_read) {
u_div_cn.addClass('set_position');};
});
Which resulting value
does .scrollTop()
get when scrolling?
The division tag
in the above example does set its position attribute to fixed by the conditional if statement
when it has reached the top of the window
.
Yet, why does in this example "greater than" .offset().top
work, in contrast to "equals to" zero
, which has not worked after many tries?
$(window).scroll(function(){
var u_div_cn = $('div#container_nav');
var u_div_cn_os_top = $('div#container_nav').scrollTop();
if ( u_div_cn_os_top == 0 ) {
u_div_cn.addClass('set_position');
};
});
The reason why I am asking is, because I thought of the equals to
to work as well right at top: 0
of the window
.
Upvotes: 0
Views: 393
Reputation: 700322
The scrollTop
function returns how many pixels the content is scrolled down, i.e. how many pixels are outside above the window.
When scrolling, you won't get an event for every single pixel that the content is scrolled. If you use the ==
operator to check the offset, you will miss it most of the time. Using the >
operator ensures that the element will become fixed as soon as its top moves out of the window at the top.
If you compare the value from scrollTop
to zero, that will only be true if you scroll down, and then scroll back up to the top.
Upvotes: 2
Reputation: 2271
It is because when the window has scrolled beyond the division tag, it add a class to fix that on the viewport.
Upvotes: 0