Reputation: 1295
I'm trying to create a piece of functionality with jQuery where you can set a class(such as "lockbox") on divs in the sidebar and they will lock to the top of the window as you scroll past them.
But I would like to implement a couple different boxes in the sidebar which will push each other out of the way as you scroll past them. The best comparison I can use is with the iPhone Contacts App, how each letter A-Z has a title bar which locks at the top. But as you scroll past A that bar gets pushed out for the B title bar to fill in. Here's a screen capture of what I'm talking about:
What would be the best technique for creating some functionality like this? I'm familiar with jQuery but I've never used properties like .offset(), so I'm struggling with even the first step to approach building this interface.
Appreciate any help in advance!
Upvotes: 2
Views: 463
Reputation: 6076
I have created a working fiddle. Link.
HTML:
<html>
<head></head>
<body>
<div id="outer_div">
<div class="lockdiv">Div A</div>
<div class="lockdivcontent">
<div class="regular">Text A 1</div>
<div class="regular">Text A 2</div>
<div class="regular">Text A 3</div>
<div class="regular">Text A 4</div>
</div>
<div class="lockdiv">Div B</div>
<div class="lockdivcontent">
<div class="regular">Text B 1</div>
<div class="regular">Text B 2</div>
<div class="regular">Text B 3</div>
<div class="regular">Text B 4</div>
</div>
<div class="lockdiv">Div C</div>
<div class="lockdivcontent">
<div class="regular">Text C 1</div>
<div class="regular">Text C 2</div>
<div class="regular">Text C 3</div>
<div class="regular">Text C 4</div>
</div>
<div class="lockdiv">Div D</div>
<div class="lockdivcontent">
<div class="regular">Text D 1</div>
<div class="regular">Text D 2</div>
<div class="regular">Text D 3</div>
<div class="regular">Text D 4</div>
</div>
<div class="lockdiv">Div E</div>
<div class="lockdivcontent">
<div class="regular">Text E 1</div>
<div class="regular">Text E 2</div>
<div class="regular">Text E 3</div>
<div class="regular">Text E 4</div>
</div>
<div class="lockdiv">Div F</div>
<div class="lockdivcontent">
<div class="regular">Text F 1</div>
<div class="regular">Text F 2</div>
<div class="regular">Text F 3</div>
<div class="regular">Text F 4</div>
</div>
<div>
</body>
</html>
Javascript:
$(document).ready(function() {
$('#outer_div').scroll(function(){
$('.lockdivcontent').each(function(){
var top = $(this).offset().top;
var lockdiv = $(this).prev();
if(top<lockdiv.height() && top>-1*($(this).height())) {
lockdiv.offset({top:1});
} else {
lockdiv.offset({top:top-lockdiv.height()-1});
}
});
});
});
CSS:
#outer_div {
width: 90%;
height: 300px;
overflow-y: auto;
overflow-x: hidden;
border: 1px solid lightgray;
padding: 0 10px;
}
.lockdiv {
width: 100%;
background-color: lightgray;
border: 1px solid;
height: 20px;
}
.regular {
width: 100%;
background-color: #FAFAFA;
height: 20px;
}
See if it helps!
Upvotes: 2