Mashable floating effect example with jQuery

Mashable, best known as social media resources website, created an awesome floating effect while user scrolling the page. Here’s a simple idea to clone this floating effect with jQuery.

Idea…

  1. Create a floating box.
  2. Initial the floating box location, put it beside the body content.
  3. While user scrolling the page, keep checking the scroll bar position.
  4. If the scroll bar y position is greater than the floating box y position, change the floating box y position dynamically.
  5. While the scroll bar y position lesser than the floating box y position, restore the original position.
  6. Use jQuery, of course.

1. HTML Layout

A simple HTML layout, header, content and footer, put a div “floating-box” above the content.


<div id="page">
  	<div id="header"><h1>header</h1></div>
	<div id="floating-box"></div>
	<div id="body">
		<h1>content</h1>
		<h2>Mashable floating effect example</h2>
	</div>
	<div id="footer"><h1>footer</h1></div>
</div>

2. Floating box 90×200

This is the box that will float smoothly while people scrolling the box. You may need to adjust the “margin-left:-100px;” a bit to suit your need.


#floating-box{
	width:90px;
	height:200px;
	border:1px solid red;
	background-color:#BBBBBB;
	float:left;
	margin-left:-100px;
	margin-right:10px;
	position:absolute;
	z-index:1;
}

3. No conflicts, please

Make sure jQuery has no conflict with other library. Highly recommend to check it.


    //avoid conflict with other script
    $j=jQuery.noConflict();

    $j(document).ready(function($) {

4. Position, position, position

Bind the jQuery scroll() event to keep checking the browser’s scroll bar position.


$(window).scroll(function () { 
		  
	var scrollY = $(window).scrollTop();
	var isfixed = $floatingbox.css('position') == 'fixed';
			
	if($floatingbox.length > 0){
			
		if ( scrollY > bodyY && !isfixed ) {
			$floatingbox.stop().css({
				position: 'fixed',
				left: '50%',
				top: 20,
				marginLeft: -500
			});
		} else if ( scrollY < bodyY && isfixed ) {
			$floatingbox.css({
				position: 'relative',
				left: 0,
				top: 0,
				marginLeft: originalX
			});
		}		
	}	
});

If the scroll bar y position is greater than the floating box y position, change the floating box y position to "marginLeft: -500". You may need to customize this value to suit your need.


	if ( scrollY > bodyY && !isfixed ) {
	   $floatingbox.stop().css({
		position: 'fixed',
		left: '50%',
		top: 20,
		marginLeft: -500
	   });
	 }

If the scroll bar y position lesser than the floating box y position, restore to the original position.


        if ( scrollY < bodyY && isfixed ) {
	   $floatingbox.css({
		position: 'relative',
		left: 0,
		top: 0,
		marginLeft: originalX
	   });
	}		

5. Done

Try playing the below example to get an idea of the works.

P.S This floating effect feature is implemented in my DiggDigg WordPress plugin.

Try it yourself


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>

<style type="text/css">
	#floating-box{
		width:90px;
		height:200px;
		border:1px solid red;
		background-color:#BBBBBB;
		float:left;
		margin-left:-100px;
		margin-right:10px;
		position:absolute;
		z-index:1;
	}
	#page{
		width:800px;
    	margin:0 auto;
	}
	#header{
		border:1px solid blue;
		height:100px;
		margin:8px;
	}
	#body{
		border:1px solid blue;
		height:2400px;
		margin:8px;
	}
	#footer{
		border:1px solid blue;
		height:100px;
		margin:8px;
	}
	h1,h2{
		padding:16px;
	}
</style>

</head>
<body>

  <div id="page">
  	<div id="header"><h1>header</h1></div>
	
	<div id="floating-box">

	</div>
	
	<div id="body">
		<h1>content</h1>
		<h2>Mashable floating effect example</h2>
	</div>
	<div id="footer"><h1>footer</h1></div>
  </div>

  
<script type="text/javascript">
	
    //avoid conflict with other script
    $j=jQuery.noConflict();

    $j(document).ready(function($) {

	//this is the floating content
	var $floatingbox = $('#floating-box');
	
	if($('#body').length > 0){
	
	  var bodyY = parseInt($('#body').offset().top) - 20;
	  var originalX = $floatingbox.css('margin-left');
	
	  $(window).scroll(function () { 
		  
	   var scrollY = $(window).scrollTop();
	   var isfixed = $floatingbox.css('position') == 'fixed';
			
	   if($floatingbox.length > 0){
			
	      $floatingbox.html("srollY : " + scrollY + ", bodyY : " 
                                    + bodyY + ", isfixed : " + isfixed);
	
	      if ( scrollY > bodyY && !isfixed ) {
			$floatingbox.stop().css({
			  position: 'fixed',
			  left: '50%',
			  top: 20,
			  marginLeft: -500
			});
		} else if ( scrollY < bodyY && isfixed ) {
		 	  $floatingbox.css({
			  position: 'relative',
			  left: 0,
			  top: 0,
			  marginLeft: originalX
		});
	     }		
	   }
       });
     }
  });
</script>
</body>
</html>

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
26 Comment threads
13 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
30 Comment authors
PetermeismNoverichardArvindDmitry Recent comment authors
newest oldest most voted
Peter
Guest
Peter

I know this post is old, but just in case it helps someone else, parseInt() requires a second parameter for the radix. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

meism
Guest
meism

hi yor all. me help to send cod. help me

Noverichard
Guest
Noverichard

how to use it on html templates?

Arvind
Guest
Arvind

Hi,
Nice work. Helped me a lot.
Keep it up. However I think

position: fixed

does not work in Safari.

Dmitry
Guest
Dmitry

Very nice script. Is there are any chance to run it with jquery 1.3.2?..

Akmal Fikri
Guest
Akmal Fikri

Any similar WordPress plugin that can do this?

Alex
Guest
Alex

It works! Nice! Have you it as WP Plugin?

Jr Trader
Guest
Jr Trader

I would really like to have a floating image for “promotions” or “contest” or even social buttons.

PedroR
Guest
PedroR

Hi.
Allow me to make you a challange. Im 1280×800 browser dimensions increase the footer height to 400px and the floating-box height to 600px. Now, the floating-box can never pass the #body. here’s (http://gestoenergy.dreamlabstudio.com/teste.html) a test I’m trying to develop. I’m having problem when the floating-box reaches the bottom of the #body. I you see the demo, you ‘ll get ir

If you or anyone accomplish let me know

Thanks

PedroR
Guest
PedroR

Ok, I succeeded. Finally, but I got problem with IE8 and IE7. Is there anyone out there who can help me or this page is dead??

nakita
Guest
nakita

How do you make it so that the “floating-box” holds at a specific X access?

You mention that the “marginLeft: -500” needs to be altered but how do you figure out exactly what it needs to be?

Is there some way to simply calculate it?

tutionspot
Guest
tutionspot

An Awesome thinking to add on website or blog thanks

Shon Gale
Guest
Shon Gale

Been trying to get by the jQuery.noConflict(); command.
I am only using jQuery 1.6.2 and jQuery.ui-1.8.1 from the jQuery UI web site and your thingie doesn’t work with it. Sorry but the jQuery UI lib is more important.

Ray
Guest
Ray

Can someone please post a way to prevent the floating box from moving off of the page to the left?

techror
Guest
techror

and how to add social facebook button into it

Julian
Guest
Julian

Sorry, I can not add html code in the comment.
I have this example: http://www.discoverdesign.info/div/index.html
and this is my code: http://www.infobuscador.com/example/index.html
I can not get something done well. Anybody can help me, please ?
Thanks

Julian
Guest
Julian

anyone can help me with this thing. I want to do something like this: http://www.discoverdesign.info/div/index.html
I lost days to find answers. Please help me.
Thanks
I have the code below:

example

body {
background:#999;
}
.container {
width:900px;
background:#FFF;
margin:0px auto;
}
.footer {
width:100%;
height:150px;
background:#06C;
}
.header {
width:100%;
height:150px;
background:#06C;
}
.content {
width:100%;
height:1200px;
background:#FFF;
}
.toolbar {
position:fixed;
bottom:0px;
width:900px;
height:40px;
background:#900;
}

2WebVideo
Guest
2WebVideo

You mentioned about jQuery conflict. Does it mean I cannot use other jquery script in the same webpage? Perhaps, in that case, the solution is to use iframe.

StatVoid
Guest
StatVoid

Is there anyway to make this work as a compliment to a footer? My goal’s to have a footer that has a form for the user to fill out. Obviously, because it’s at the bottom of the page, they might overlook the fact it’s there. So I’d like a button on the bottom of the screen that’s like 150px by 150px and about 15px from the bottom, when you reach the footer though, I want that same button to go to the top of the footer (which will be roughly 300px). As if the footer is told, “do not cross… Read more »

Andre
Guest
Andre

Hi, was looking for the same functino and just came across this jquery example menu that stops at the footer, maybe thats what u mean? http://plugins.jquery.com/files/stickyfloat_0.htm

Julian
Guest
Julian

Thanks Andre. That is what i need

mark lancaster
Guest
mark lancaster

any ideas for how to make it fade into position instead of just popping into frame?

Ricky
Guest
Ricky

Holy shit. Your ads autoplay with audio and have no pause or mute button.

No.

Matt
Guest
Matt

Thanks for the great tutorial.

There’s one thing though. The script would be even better if the floating box stopped floating when its bottom reached the top of the footer or at least the bottom of the window (the end of the page).

In other words, how do you make it “float” only between certain elements, lets say between the header and the footer?

ossama
Guest
ossama

thank you. I was looking for this trick a long time ago.

Paul MacLean | tbk Creative | Web Design and Web Marketing
Guest
Paul MacLean | tbk Creative | Web Design and Web Marketing

Hi there, I have created a plugin for wordpress that does this. It’s still in Beta but its easy to use…give it a try,http://www.tbkcreative.com/the-lab/wordpress-social-media-button-plugin/

erwin
Guest
erwin

how can you make it scroll smoother that default javascript scroll?

dattai
Guest
dattai

that’s very cool

Thanks alot

Sean O
Guest
Sean O

Works fine in Chrome & Firefox (PC), but fails in IE (fixed positioning issues).

Jay Edgar
Guest
Jay Edgar

It’s also not working in IE 9.