Reputation:
When I change variable to 0, it doesn't work. Why must I use variable instead of just "0"?
Use 0 number instead of variable name and you will see. fiddle
$(function() {
var zero = 0;
$(window).scroll(function() {
var top = $(this).scrollTop();
if (top > zero) {
$("nav").hide();
} else if (top < zero) {
$("nav").show();
}
zero = top;
});
});
body {
height: 1000px;
}
nav {
width: 100%;
height: 75px;
background: #333;
position: fixed;
top: 0;
left: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav></nav>
Upvotes: 0
Views: 26
Reputation: 218960
Why i must use variable instead of just "0"?
Because you're modifying the value. Here's what your code would look like if you tried to use a literal value instead of a variable:
$(window).scroll(function() {
var top = $(this).scrollTop();
if (top > 0) {
$("nav").hide();
} else if (top < 0) {
$("nav").show();
}
0 = top; // <-- here is the problem
});
Clearly, that last line doesn't make sense. You can't modify a literal value. Storing a value and modifying it over time is exactly what a variable is for. So in this case you need to use a variable.
Upvotes: 1