Wow, I've been tinkering away for hours and can't seem to crack this code puzzle.
Let's dive into some CSS:
#wrapper {
margin: 0 auto;
padding: 0 20px;
width: 960px;
}
#wrapper .block {
width: 920px;
height: 690px;
}
#wrapper .container {
background-color: #000;
width: 920px;
height: 80px;
}
#wrapper .container div {
margin: 20px auto 0;
width: 510px;
height: 35px;
}
Seems pretty straightforward. We have a container nested within a block inside a wrapper. When the user scrolls past a certain point on the page, I want the container to stick to the top of the page and expand to the full width of the window. Likewise, it should revert back to its original state when scrolling in the opposite direction.
I've managed to make the fixation work using jQuery:
$(function() {
$(window).scroll(function() {
if ($(this).scrollTop() >= 690) $('.container').css({
'position' : 'fixed',
'top' : '0',
'left' : '50%',
'margin-left' : '-460px'
});
if ($(this).scrollTop() < 690) $('.container').removeAttr('style');
});
});
However, I'm struggling to figure out how to smoothly expand and retract the width of the container while keeping everything centered with no glitches or delays. The desired effect is for the container to gradually widen from its original width to fill the window after the scroll position reaches or exceeds 690px
, and then shrink back before that point.
Here's my basic understanding:
$(function() {
$('window').scroll(function() {
if ($(this).scrollTop() >= 690) $('.container').animate({'width' : '100%'});
if ($(this).scrollTop() < 690) $('.container').animate({'width' : '920px'});
});
});
The challenge lies in integrating these two concepts seamlessly. I considered using a hidden div
behind the container that animates once the scroll conditions are met, but that approach isn't yielding results either.
To help visualize, here's a representation of what I'm aiming for:
Do I need to tweak my CSS or jQuery, or both? Should I abandon ship and explore CSS3 transitions as an alternative? Or would that only complicate things further? It's driving me crazy that something seemingly simple is proving so elusive, and I'll lose my mind if there's a ridiculously easy solution I've overlooked, haha.
Any guidance or feedback would be greatly appreciated. Thank you!
Update
Some HTML:
<div id="wrapper">
<div class="block">Some content</div>
<div class="container">
<div>A few navigation links</div>
</div>
<div class="main">Main content</div>
</div>
(P.S. - I know the semantics are messy, haha. This is all experimental. Thanks.)