Reputation: 507
i've tried every single thing on the internet i could have find and as i'm a complete noob in js and am trying to learn some more complicated css i don't know why this scroll then fixed code is not working and don't know how to get it to work. Basically i have a header wrapper which includes header_pic of 373px height and header_nav which is 50 px in height. I just want to scroll to top of the header_nav and then set it to position fixed but every single one i used didnt work for some reason and i did include google's jQuery CDN in head area in my html page and then i included my external scrip.
Here's example of my webpage in jsfiddle: https://jsfiddle.net/pyr2h0c5/
var elementPosition = $('#header_nav').offset();
$(window).scroll(function () {
if ($(window).scrollTop() > elementPosition.top) {
$('#header_nav').css('position', 'fixed').css('top', '0');
} else {
$('#header_nav').css('position', 'static');
}
});
Thanks for the patiance :D
Upvotes: 1
Views: 8215
Reputation: 16191
As far as I understood, you linked jQuery in your code and then included your script. You put the script in the <head>
which makes your selected elements undefined at the time when the script runs, as they are rendered AFTER the script (like the #header_nav
for example).
Error that's possibly thrown on scroll:
Uncaught TypeError: Cannot read property 'top' of undefined
Solution:
Leave jQuery where it is but take your script out of <head>
and put it right before the closing </body>
tag. All should be peachy:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<!-- Your HTML -->
<script type="text/javascript">
var elementPosition = $('#header_nav').offset();
$(window).scroll(function () {
if ($(window).scrollTop() > elementPosition.top) {
$('#header_nav').css('position', 'fixed').css('top', '0');
} else {
$('#header_nav').css('position', 'static');
}
});
</script>
</body>
</html>
Upvotes: 6
Reputation: 9813
You didn't include jquery in your jsfiddle, included it, and works...
No code changes...
var elementPosition = $('#header_nav').offset();
$(window).scroll(function () {
if ($(window).scrollTop() > elementPosition.top) {
$('#header_nav').css('position', 'fixed').css('top', '0');
} else {
$('#header_nav').css('position', 'static');
}
});
Add something like
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
in your real page's <head>
, or try to download jQuery to local and include it locally.
Upvotes: 1