Create a Sexy Persistent Header with Opacity Using MooTools or jQuery

By  on  

I've been working with the Magento eCommerce solution a lot lately and I've taken a liking to a technique they use with the top bar within their administrative control panel. When the user scrolls below a specified threshold, the top bar becomes attached to the top of the window and the opacity set to 50%. I've implemented this technique in my current design and have gotten numerous requests for a tutorial so...here you go!

The HTML


A DIV with whatever elements and structure you'd like within it.

The CSS

#uberbar	{ 
	border-bottom:1px solid #eb7429; 
	background:#fc9453; 
	padding:10px 20px; 
	position:fixed; 
	top:0; 
	left:0; 
	z-index:2000; 
	width:100%;
}

Using position:fixed will allow the bar to degrade well within Internet Explorer 6 by simply keeping the bar at the top. Be sure to position the element at 0x0and set a 100% width. You may style the DIV any way you'd like but I'd recommend keeping the height of your element to a minimum.

The MooTools JavaScript

window.addEvent('domready',function() {
	(function() {
		var topbar = $('uberbar').set('tween',{ duration: 200 }), topDistance = 30, fadeTo = 0.5;
		var topbarME = function() { topbar.tween('opacity',1); }, topbarML = function() { topbar.tween('opacity',fadeTo); };
		var events = {
			mouseenter: topbarME,
			mouseleave: topbarML
		};
		var ss = new ScrollSpy({
			min: topDistance,
			max: window.getScrollSize().y + 1000,
			onLeave: function() {
				topbarME();
				topbar.removeEvents(events);
			},
			onEnter: function() {
				topbarML();
				topbar.addEvents(events);
			}
		});
	})();
});

Once all of our settings are in place, I use my ScrollSpy plugin to set minimum and maximum (enter and exit) vertical scroll values and add/remove mouseover and mouseenter events accordingly. The events are added to return the bar t0 100% opacity when the user mouses over the bar. ScrollSpy allows you to focus on functionality and not worry about keeping track of scroll position. You'll notice that I've not accounted for making the bar scroll in IE6 using JavaScript -- if you'd like this effect to work in IE6, I recommend using ScrollSpy's onTick(pos) method to position the bar while scrolling.

The jQuery JavaScript

$(document).ready(function() {
	(function() {
		//settings
		var fadeSpeed = 200, fadeTo = 0.5, topDistance = 30;
		var topbarME = function() { $('#uberbar').fadeTo(fadeSpeed,1); }, topbarML = function() { $('#uberbar').fadeTo(fadeSpeed,fadeTo); };
		var inside = false;
		//do
		$(window).scroll(function() {
			position = $(window).scrollTop();
			if(position > topDistance && !inside) {
				//add events
				topbarML();
				$('#uberbar').bind('mouseenter',topbarME);
				$('#uberbar').bind('mouseleave',topbarML);
				inside = true;
			}
			else if (position < topDistance){
				topbarME();
				$('#uberbar').unbind('mouseenter',topbarME);
				$('#uberbar').unbind('mouseleave',topbarML);
				inside = false;
			}
		});
	})();
});

The above jQuery code will accomplish the same effect.

This isn't the type of effect you'd want to use on most websites but it can be a great utility for websites that need to be highly functional.

Recent Features

  • By
    Vibration API

    Many of the new APIs provided to us by browser vendors are more targeted toward the mobile user than the desktop user.  One of those simple APIs the Vibration API.  The Vibration API allows developers to direct the device, using JavaScript, to vibrate in...

  • By
    How to Create a Twitter Card

    One of my favorite social APIs was the Open Graph API adopted by Facebook.  Adding just a few META tags to each page allowed links to my article to be styled and presented the way I wanted them to, giving me a bit of control...

Incredible Demos

Discussion

  1. Great post. I too have recently finished my first project using Magento and this toolbar caught my eye too – your script will come in very helpful on future projects.

  2. I already loved this effect on your website and was wondering when you would share the script/write a tutorial about it. Thanks for this great lesson and keep up the great work!

  3. David, this is really nice tip :).
    Is very very useful if someone use with some design skills ;)

    Thx!

  4. Surely this will come in handy in the category of “tools for admin interface”.
    Thanks!

  5. ohh god it looks so ugly. It distracts me from the content.

    I don’t know I guess im different

  6. +1 for Freddy. It reminds me your blog David…

  7. Nice but it doesn’t play nicely with the code blocks you have in your post in FF3.5.5.

  8. Yikes persistent headers (or anything for that matter) is just distracting. The only time it works, in my opinion of course, is when you’re customizing a shopping cart (like configuring a laptop on ibuypower or those types of sites) and when you make a change the persistent final price changes.

    In this case, I find the blur just distracting – it’s a frame (and I know how we all feel about frames) but with 50% opacity. I don’t get why anyone would like it. The other one you made David, the “back to top” image that appears when you reach a certain point in the page was elegant but this is just a transparent frame that distracts. I think it would work with what you said, an administrative control panel (in which case you wouldn’t even need to make it partially transparent) but for just a website with content it’s better off “not being persistent” imo.

  9. john

    does not work in opera.

    fail.

    • ness

      It work! Just in Opera the text position inside the footer a bit lower, but when you rollover it, the position back to right position.
      Anyone know how to fix it?

  10. While I still think it is a great quality article. I am sure I will use this sooner or later. Thanks David for the Jquery version also

  11. senshikaze

    I like the look, but i dislike how you implemented it. It is distracting, and kinda breaks overall look of the site. Like a header over a header when at the top of the page. I think the simple “to top” element on the right was much better for general navigation. the change in transparancy (and therefore, color) when the mouse hovers is extremely distracting. I don’t know why, but i always feel like I am having to stop to read your webpage. I seem to read “high” in the browser window and your bar gets in the way of that.
    And funnily, enough, I have no problem with persistent(“sticky”) footers. It just seems persistent headers don’t work for me.
    I am not demanding you to change anything, and I will continue to read your site, but I wanted to give one users feedback.

  12. @john: Using Opera: Fail.

    • Hi,

      I use your code for my website, it works in opera.
      But the content inside the footer a bit lower that other browser.
      When you rollover it the position move to the correct position.

      Can give me some suggestion?

      Btw, is it work in iphone? or is only me.

      Thanks^^

  13. Gabriel

    Pimpi Header, :S:S

  14. Alex Sokolov

    @David Walsh: Tell that to at least 50 mil users around world using Opera. Your attitude is fail. Though persistent header on your site and in demos works well in Opera.

  15. wow great plugin for my jQuery :D thank for sharing it and this work arround for my site :D

  16. Chris the Developer

    @Alex Sokolov – Your grasp of sarcasm is fail.

  17. thanx for perfect js code :)

  18. Whats with the anti Opera. There developers have created some of the best web-features to date. Go look at Opera 10.10 they are consistently first to implement loads of cool features that other browsers slowly adopt.

    I like the demo though David, it would work well on social networking sites like myspace where pagination is only partly implemented and you cripple your index finger scrolling back up through 1000 comments of animated gif’s.

  19. It is cute for some proyects

  20. @Alex Sokolov: About Opera… I don’t think anyone has really something against it… It’s just that development tend to be made for the browsers with the most user base.
    http://www.w3schools.com/browsers/browsers_stats.asp

    Nothing personal.

    I found the script useful (in particular case, as exposed earlier), but I don’t really like having something not quite visible (opacity 50%) that is persistent… I did prefer the subtle “Back to top” link that appeared (and I have used that technique on my own websites).

  21. Chris the Developer

    Just to reiterate some of what Nick said; Nobody is against Opera (I mean; if David can defend perfecting things in IE6 then how on earth can you take what he said seriously about Opera…?).

    I don’t, however, believe that Opera has an insignificant user-base (as Nickolas would suggest). I think it’s a wonderful browser, as I’m sure many millions of others do, and I wouldn’t trust w3schools.com to tutor my mom on CD-ROM usage, let alone report accurate browser usage stats…

  22. To fan the flames: my Opera comment was a joke. Kind of…

  23. @Chris the Developer: Precisely. The stats are just for “reference”, but they don’t really give a real feeling of the browser usage. The stats are for the w3schools website only and may (or may not) reflect reality.

    Kind of? … ;)

  24. Thanks for sharing this. I modified and simplified it a bit for a website of mine:

    var opacity = 1, topDistance = 100;
    $(window).scroll(function() {
    position = $(window).scrollTop();
    if(position <= topDistance) {
    $('#uberbar').css('opacity',opacity-(position/100));
    }
    else {
    $('#uberbar').css('opacity','0');
    }
    });
    

    It slowly disappears/reappears for the top 100 pixels of scrolling. I didn't like the fadeTo effect because there was a delay. Changing the CSS produces an immediate effect.

    Thanks for the inspiration!

  25. Thanks for sharing this. I tweaked the code a little bit. I didn’t like how the fadeTo works, so I just change the CSS opacity property directly.

    Click my name to see my blog post about it.

    Thanks for the inspiration!

  26. Chris

    Sorry about the “double” post. My first one didn’t show and I didn’t get any indication that it was needing to be approved…

  27. Flash content – IE YouTube & Vimeo videos appear OVER the bar. Wmode = transparent fix?

  28. Flash content – IE YouTube & Vimeo videos appear OVER the bar. Wmode = transparent fix?

    yes ?

  29. This is really neat. I am going to look into implementing it on my wiki, Wiki4Coders. Thanks for this tutorial! We sure could use someone like you!

  30. @rickyH: Default cursor on text, none-native OS scrollbar and button, you call that good web features?

    If its rendering engine didn’t have some stuff from IE and fixed the cursor/buttons/scrollbars then it would actually be a pretty snazzy browser.

  31. I think I like the jQuery approach better, due to not having to load another script, saving room for a different HTTP request. However with jQuery you have to add a few extra lines so that continuous mouseover, will not trigger it to go crazy and keep fading in and out even when the mouse is not on the element. All be it the effect is greatly achieved either way.

  32. Create a Sexy Persistent Footer?

  33. @yokser: Sexy footers exist?

  34. Nick

    My main gripe with this on your site is the aforementioned problem with the bar flickering as it passes over code blocks. I see this in Firefox 3.5.

    If you could fix that I’d be a fan as I think it’s pretty neat and unobtrusive in general. Good job. :)

  35. steve

    to be honest, I found that 50% opacity foolishness INTENSELY annoying and distracting
    …. in frustration. i Ended up using adblock to block the div in which it sat :) aaaaahhhh relief!

  36. Federico

    I added a little change to jquery version.
    I added a new var for the id, so you only have to change it and its ready to go at any id.
    For the footer version, i only change at the css the rule, and work pretty good (bottom for top)
    The only problem (as usual) are the IE browsers.

  37. Viper

    Thanks for useful techniques. I’ve implement this bar in my project as toolbar for quick access to site function(such as bookmarks, alphabets sorting, etc.).
    And because header appears at top of page, I think we must set top margin for body(if site start at top of page w/o margin).

    Just write

    $("body").css({"margin-top": $("#userbar").outerHeight(true)});
    

    where #userbar is our Sexy Header )

    • Me

      Hey, m8, how and where did u add

      $("body").css({"margin-top": $("#userbar").outerHeight(true)});
  38. Daniel

    The jQuery version code is not valid ;/

  39. Thx for this code!
    I took parts of it for a filter bar. The main difference is, that the filter bar is in the middle of the page content and not at the top.
    As you scroll down the page, it “hooks” to the top and scrolls with it, as seen in the Magento admin backend.

    Here’s my code:

    $(document).ready(function() {
    	(function() {
                
    		//settings
    		var topDistance = $('.filterbar').first().position().top;
    		var inside = false;
    		$(window).scroll(function() {
    			position = $(window).scrollTop();
    			if(position > topDistance && !inside) {
    				$('.filterbar').attr('style', 'position: fixed; top: 0');
    				inside = true;
    			}
    			else if (position < topDistance){
    				$('.filterbar').attr('style', 'position: static; top: 0');
    				inside = false;
    			}
    		});
    	})();
    });
  40. amit

    hey …

    when i scroll down the page using mouse wheel it works but when i used scroll bar it take little-bit more time to fade out ( in jquery demo ) .

    and other one work fine.

  41. amit

    hey …

    when i scroll down the page using mouse wheel it works but when i used scroll bar it take little-bit more time to fade out ( in jquery demo ) .

    and other one work fine.

  42. andrai

    A magento frontend feature like this would be great! A persistent header with shopping cart, account, wishlist etc.. and also facebook/twitter icons. You should make a module!

  43. kenneth

    Hey I really Like this bar, but for some reason I cant get the fade to take effect. I have it on my page and everything, but when I decend it stays the same – any ideas?

  44. Hi,

    The website i made looks fine in most of the browsers but when i try to view it in iphone, the footer stick in the middle of the page….
    Can anyone help me?

  45. Patrick

    Thanks David!
    How would I make the effect opposite? I’d like to make the uberbar appear transparent at top, but become more opaque during scroll. Works for scrolling when I flip flop the opacity numbers, but on initial load the uberbar always appears opaque.

  46. I got the persistent header to work but how would i apply it to my top bar so that my top bar with the navigation would have this function?

  47. Just to reiterate some of what Nick said; Nobody is against Opera (I mean; if David can defend perfecting things in IE6 then how on earth can you take what he said seriously about Opera…?).

    I don’t, however, believe that Opera has an insignificant user-base (as Nickolas would suggest). I think it’s a wonderful browser, as I’m sure many millions of others do, and I wouldn’t trust w3schools.com to tutor my mom on CD-ROM usage, let alone report accurate browser usage stats…

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!