Well, I have this navigation menu which is static but I want to make it flow smoothly whenever user scrolls his page down or up... Please help with the code because I already have tried to do something but everything went bad.
Code:
<div id="menu">
<ul>
<li class="page_item">
<a href="<?php bloginfo('url'); ?>" title="Go home">Home</a>
</li>
<?php wp_list_pages('&title_li=&exclude=6386'); ?>
<?php
if(is_user_logged_in() && !current_user_can('subscriber')) :
?>
<li class="page_item">
<a href="<?php bloginfo('url'); ?>/tasks/" title="Your task list">Tasks</a>
</li>
<?php
endif;
?>
<?php
if(!is_user_logged_in()) :
?>
<li class="page_item">
<a href="<?php bloginfo('url'); ?>/wp-admin/">Log in</a>
</li>
<?php
endif;
?>
</ul>
</div>
I want this whole thing to float, how am I supposed to do this?
I tried to add this script and give menu class="scroller":
$(window).load(function(){
$(window).scroll(function(){
if($(window).scrollTop()>60){
$('.scroller').css('position', 'fixed');
$('.scroller').css('top', 0);
} else {
$('.scroller').css('position', 'relative');
$('.scroller').css('top', 60);
}
});
});
But no luck..
The CSS property 'top' doesn't work with relative positioning. Try absolute instead.
$(window).scroll(function(){
if($(window).scrollTop()>60){
$('.scroller').css('position', 'fixed');
$('.scroller').css('top', 0);
} else {
$('.scroller').css('position', 'absolute');
$('.scroller').css('top', 60);
}
});
EDIT : You'll need to add a margin to the element above or below where you want the scrollbar to appear to create a gap for it.
First of all, because you're using jQuery, you don't have to bind the onLoad
event to do it. Just bind the onDomReady
pseudo-event, without to create any other class (you already have the ID). That said, you need to listen for the onScroll
event of the document. Try this:
$(function(){
$(document).on('scroll',function(){
var $this = $(this),
$menu = $('#menu'),
scrl = $this.scrollTop(),
menuHeight = $menu.height();
if( scrl > menuHeight ) {
$('#menu').css({
'position': 'fixed',
'top': 0
});
} else {
$('#menu').css({
'position': 'relative',
'top': menuHeight
});
}
});
});
This should works fine for your needs.
Here's a jsFiddle to test the code.
EDIT : code updated to dynamically handle every menu height.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.