Reputation:
I fix a div to the bottom of the window once it's position is scrolled out of window view. I then 'unfix' it when it's postion is scrolled back into view. If the scrolling is done slowly there is a horrible flickering of postions. Is there a way of combating this?
DEMO https://jsfiddle.net/3146nxLx/
var initSet = false;
$(window).scroll(function() {
if (isScrolledIntoView($('#myDivTrigger'))) {
if (!initSet) {
initSet = true;
}
$("#myDiv").removeClass('fixed');
} else if (initSet) {
$("#myDiv").addClass('fixed');
}
});
function isScrolledIntoView(elem) {
var $elem = $(elem);
var $window = $(window);
var docViewTop = $window.scrollTop();
var docViewBottom = docViewTop + $window.height();
var elemTop = $elem.offset().top;
var elemBottom = elemTop + $elem.height();
return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
Upvotes: 1
Views: 990
Reputation: 39342
Yes, the problem is bcz after setting position: fixed;
to myDiv
browser removes it from normal flow of DOM...
you can apply height to the wrapper and then register scroll handler.. here is another possible solution without cloning or use an extra block..
Here is Fidde
Upvotes: 0
Reputation: 24723
this is because you are setting a fixed element, then the trigger
is popping up into it's place, thus becoming visible. You need to create a wrapper, give it a position relative and then set the trigger to position absolute. This way the trigger's position will not move when the fixed div's postion changes.
DEMO https://jsfiddle.net/3146nxLx/1/
<div id="myDivWrap">
<div id="myDiv">
<p>
This should be fixed once it comes into view and then goes out of view.
</p>
</div>
<span id="myDivTrigger">trigger</span>
</div>
You could even give the trigger a bottom
value so the transition is smoother. Yes and give it a left value also.
DEMO https://jsfiddle.net/3146nxLx/3/
Here's an example, semi based on the logic as suggested by @Lionel. You clone the div and then add it. This also means you do not need a trigger.
DEMO https://jsfiddle.net/3146nxLx/4/
Upvotes: 1