Reputation: 505
I have <header>
and <nav>
blocks that are affected by JavaScript. What I would like is for the <nav>
block to become position: static
if the user resizes the window to smaller than 1119px wide. The script currently works only on page load, but does not detect resize.
I've tried applying the solution from this question, but with no luck. Here's a link to the webpage in question:
Here's my JavaScript so far:
<script>
$(document).ready(function(){
var $window = $(window);
function checkWidth() {
windowsize = $window.width();
if (windowsize > 1119) {
$(window).scroll(function() {
if ($(this).scrollTop()>119)
{
$('header').fadeOut();
$('nav').css({position: 'fixed', top: '0px'});
}
else
{
$('header').fadeIn();
$('nav').css({position: 'absolute', top: 'auto'});
}
});
}
else {
$('nav').css({position: 'static', top: '0px'});
}
}
// can trigger the resize handler instead of
// explicitly calling checkWidth()
$(window).resize(checkWidth).resize();
});
</script>
Upvotes: 1
Views: 2277
Reputation: 6057
Use media queries in CSS (add somewhere in css)
@media (max-width: 1119px) {
nav {position: 'static' !important; opacity: 1 !important;}
}
You can simplify your js
<script>
$(document).ready(function() {
$(window).scroll(function() {
if ($(this).scrollTop()>119) {
$('header').fadeOut();
$('nav').css({position: 'fixed', top: '0px'});
} else {
$('header').fadeIn();
$('nav').css({position: 'absolute', top: 'auto'});
}
});
});
</script>
The scroll function will still execute, but will not make any visual changes. This is good, because it will keep track of the changes and resizing after scrolled down will react properly.
Upvotes: 1
Reputation: 2975
Use .trigger() for this:
$(window).resize(checkWidth)
.trigger('resize');
Try following demo. When you open console try to resize window in console log should be outputed when ever you resize it.
Try this code in your server:
$(document).ready(function(){
var $window = $(window);
$window.on('resize', function () {
windowsize = $window.width();
if (windowsize > 1119)
{
$window.scroll(function() {
if ($(this).scrollTop()>119)
{
$('header').fadeOut();
$('nav').css({position: 'fixed', top: '0px'});
}
else
{
$('header').fadeIn();
$('nav').css({position: 'absolute', top: 'auto'});
}
}).scroll();
}
else
{
$('nav').css({position: 'static', top: '0px'});
$('header').fadeIn();
$window.off('scroll');
}
}).resize();
});
Upvotes: 1
Reputation: 7784
Your current code only runs once when the document loads. You need to use something like:
$(window).on('resize', function () {
// your code here
});
So you bind
to the $(window)
Upvotes: 0