jQuery Sticky Menu Plugin
This is a very simple jQuery plugin (code sample) which I’ve written for my blog to make the top horizontal menu bar sticky when a user scrolls down the page. Actually there are a lot of sites on the internet (specially blogs) who are using this technique now a days to make the main menu bar sticky and to make the site navigation easy for a user even when the user is middle or bottom of the page reading an article. I found this as very useful and decided to make a sticky menu on my site too. So I’ve written some code (without plugin) and achieved the sticky menu style on my site too but suddenly I’ve decided to make it as a plugin (probably I was bored) so I did it and I’m sharing the code sample. Any one can edit this code to make it better fit on his/her site (if anyone decides to use this ugly code).
(function( $ ){ $.fn.stickyMenu = function( options ) { var $this = this, defaults = { 'left' : 0, 'top' : 0, 'menu_offset_top' : $this.offset().top }, settings = $.extend({}, defaults, options); $(window).on('scroll.stickyMenu', function(){ if ($(window).scrollTop() > settings.menu_offset_top) { $this.css({ 'position': 'fixed', 'top':settings.left, 'left':settings.top, 'zIndex':9999 }); } else { $this.css({ 'position': 'relative', }); } }); return $this; }; })(jQuery);
Using this plugin is simple
$(function(){ // "navigation-wrap" is my menu id $('#navigation-wrap').stickyMenu(); });
This is just a skeleton and the only job it’s doing that, on the $(window).scroll()
event it’s checking the scrollTop
property and if the scrollTop
property is grater than the initial $('menubar').offset().top
value then it’s changing the position from relative
to fixed
and also setting the top : 0
and left : 0
and also z-index : 9999
to make sure that other elements can’t overlap it and the options
is not being used but someone can override the default values, that’s it.