Real-time update absolute positioned div when scrolling - javascript

Let me explain the situation:
There is a relative positioned sidebar. After scrolling past the top of the main-content this sidebar changes to absolute and is then real-time updated to the top position in the window (scrollTop of the window).
The problem is that it is really slow and choppy (in Firefox) because it is updating the whole time. How can I update the position 'real-time' without so much load?
Currently it looks like this:
var headerOffset = $('#main-content').offset().top;
$(document).on('scroll', function() {
if( ($(document).scrollTop() + 15) > $('#main-content').offset().top ){
$('#sidebar').addClass('fixed');
$('#sidebar').css('top', ( $(document).scrollTop() - headerOffset) + 15 );
} else {
$('#sidebar').removeClass('fixed');
}
});
Thanks in advance :)

In case you want to do all the Javascript hassle because you have unpredictable headers and don't know the exact position of main content it wold be enough to set the ccs to fixed and just calculate the position on start.
var headerOffset = $('#main-content').offset().top;
$('#sidebar').css('top', headerOffset);
like here:http://jsfiddle.net/4amdr/
Thats the only way I can imagine why you don't want to use a fixed top and leave js out.

you should use affix from twitter bootstrap : Bootstrap's affix

What about this :
=> http://jsfiddle.net/8XVXj/1/ or a full exemple : http://jsfiddle.net/8XVXj/2/
var headerOffset = $('#main-content').offset().top;
$(document).on('scroll', function(){
if( ($(document).scrollTop() + 15) > $('#main-content').offset().top ){
if($('#sidebar').hasClass('fixed') === false) {
$('#sidebar').addClass('fixed');
$('#sidebar').css('top', ($(document).scrollTop() - headerOffset) + 15 );
}
} else {
$('#sidebar').removeClass('fixed');
}
});
I add only once the position fixed.

Related

How to make an element become fixed when 50px from the top of the screen

I have a html div element that scrolls with the page but I would like it to become fixed once it reaches 50px from the top of the screen...
How is this done?
My div id is #box
Thanks!
-Ina
If you want it to be fixed at the top of the page at some distance from the top, you can check the top offset of the element and change the class when it reach the distance you want.
Here is the jquery code for your reference
jQuery(document).scroll(function() {
var documentTop = jQuery(document).scrollTop();
console.log('this is current top of your document' + documentTop );
//box top is 891
if (documentTop > 841) {
//change the value of the css at this point
jQuery("#box").addClass("stayfix");
}
else
{
jQuery("#box").removeClass("stayfix");
}
});
You need to be more specific about what have you done so far. For eg, how did you make the div element to scrolls inside the page. using css or js/jquery animation features?That will help us to give more specific answer.
**Edited According to your fiddle.
They are right, this question is duplicate. Here is a code I made with answers from the forum.
var box_top = $("#box").offset().top;
$(window).scroll(function (event) {
if ($(window).scrollTop() >= (box_top - 50)) {
$("#box").css({position:"fixed",top:"50px"});
} else {
$("#box").css({position:"relative"});
}
});
Hope it helps anyway.
https://jsfiddle.net/ay54msd5/1/
Try something like this. It's a solution using jquery (hopefully not a problem) that checks the scrollHeight of the page every time the page scrolls. If the scrollHeight is greater than a certain threshold, the element becomes fixed. If not, the element is positioned relatively (but you can do whatever you want in that case.
$(document).ready(function() {
var navFixed = false;
var $box = $("#box");
var topHeight = 50;
$(document).scroll(function() {
if ($(document).scrollTop() >= topHeight && !navFixed) {
$box.css("position", "fixed");
navFixed = true;
}
else if ($(document).scrollTop() < topHeight && navFixed) {
$box.css("position", "relative");
navFixed = false;
}
});
});
You would have to write some additional CSS targeting the #box element that tells it what coordinates you'd like it to be fixed to.

Making an element disappear when at the bottom of the page

I am making a website but I don't know much about javascript or jquery. I have a down arrow on my homepage showing that there is more information but I want it to go away when the user scrolls to the bottom of the page because it is then not needed because they can't scroll down anymore. I know I will need javascript or jquery to do this but I don't even know where to start with it. Help!
Try something like this :
document.onscroll = function() {
if (window.innerHeight + window.scrollY > document.body.clientHeight) {
document.getElementById('arrow').style.display='none';
}
}
Where 'arrow' is the id of the image.
Using jquery:
$(window).scroll(function(){
var numPix = 200; // number of pixels before bottom of page that you want to start fading
var op = (($(document).height() - $(window).height()) - $(window).scrollTop()) / numPix;
if( op <= 0 ){
$("#thing-to-hide").hide();
} else {
$("#thing-to-hide").show();
}
$("#thing-to-hide").css("opacity", op );
});

Do not execute jQuery script if CSS is of particular value

On my website, I have a sidebar DIV on the left and a text DIV on the right. I wanted to make the sidebar follow the reader as he or she scrolls down so I DuckDuckGo'ed a bit and found this then modified it slightly to my needs:
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(function(){
var $sidebar = $('#sidebar'),
sidebarOffset = $sidebar.offset(),
$window = $(window),
gap = $('#header').css('marginBottom').replace(/[^-\d\.]/g, ''),
distance = ($window.scrollTop()) - (sidebarOffset.top - gap),
footerHeight = $('#footer').outerHeight();
$window.scroll(function(){
distance = ($window.scrollTop()) - (sidebarOffset.top - gap);
if ( distance > 0 ) {
$sidebar.css({'top': gap + 'px', 'position' : 'fixed'});
} else {
$sidebar.css({'top': '0', 'position': 'relative'});
}
})
});
});//]]>
</script>
And it works just like I want it to. However, my website uses Skeleton framework to handle responsive design. I've designed it so that when it goes down to mobile devices (horizontal then vertical), sidebar moves from being to the left of the text to being above it so that text DIV can take 100% width. As you can probably imagine, this script causes the sidebar to cover parts of text as you scroll down.
I am completely new to jQuery and I am doing my best through trial-and-error but I've given up. What I need help with is to make this script not execute if a certain DIV has a certain CSS value (i.e. #header-logo is display: none).
Ideally, the script should check for this when user resizes the browser, not on website load, in case user resizes the browser window from normal size to mobile size.
I imagine it should be enough to wrap it in some IF-ELSE statement but I am starting to pull the hair out of my head by now. And since I don't have too much hair anyway, I need help!
Thanks a lot in advance!
This function will execute on window resize and will check if #header-logo is visible.
$(window).resize(function() {
if ($('#header-logo').is(':visible')) {
// Your code
}
});
I think you need to check this on load to, because you don't know if the user will start with mobile view or not. You could do something like this:
$(window).resize(function() {
if ($('#header-logo').is(':visible')) {
// Your code
}
}).resize();
This will get executed on load and on resize.
EDIT: You will probably need to turn off the scroll function if #header-logo is not visible. So, instead of create the function inside the scroll event, you need to create it outside:
$(window).resize(function() {
if ($('#header-logo').is(':visible')) {
var $sidebar = $('#sidebar'),
sidebarOffset = $sidebar.offset(),
$window = $(window),
gap = $('#header').css('marginBottom').replace(/[^-\d\.]/g, ''),
distance = ($window.scrollTop()) - (sidebarOffset.top - gap),
footerHeight = $('#footer').outerHeight();
function myScroll() {
distance = ($window.scrollTop()) - (sidebarOffset.top - gap);
if ( distance > 0 ) {
$sidebar.css({'top': gap + 'px', 'position' : 'fixed'});
} else {
$sidebar.css({'top': '0', 'position': 'relative'});
}
}
$window.on('scroll', myScroll);
} else {
$(window).off('scroll', myScroll);
}
});
Didn't test it, but you get the idea.
$("#headerLogo").css("display") will get you the value.
http://api.jquery.com/css/
I also see you only want this to happen on resize, so wrap it in jquery's resize() function:
https://api.jquery.com/resize/

How to make a .fixed sticky item's "margin-top" relative to the size of the sticky item?

This is my first question. I am having trouble with a image I am trying to stick when it reaches the top of the page after scrolling.
Check out this jfiddle - it is not mine but comes close to representing my question
http://jsfiddle.net/vBy5w/
(I am aware that I can input a set "margin-top" to make this work but when the browser size changes then the image size will respond and will throw off the set margin.)
So far I have achieved this by using the code below to effect the Div Id = Picture1 in my html
<div id="picture1"><img src="img/empty-restaurant.png" alt="Why do your customers not come back?" style="max-width:100%;height:auto;"> </div>
When this picture "sticks" the test below the image will jump up, I fixed this by including the last line of the .js but by stating a fixed "margin-top" it means that there will be a jump if the margin size is not correct depending on browser size.
Is there a way to make this Margin variable or relative to the height of the "stick"-ed item? And if so how?
Thanks guys!
$(document).ready(function() {
var s = $("#picture1");
var pos = s.position();
$(window).scroll(function() {
var windowpos = $(window).scrollTop();
//$("#header_left").html("Distance from top:" + pos.top + "<br />Scroll position: " + windowpos);
if (windowpos >= pos.top) {
s.addClass("stick");
} else {
s.removeClass("stick");
}
This is the part that needs changing - the first "margin-top" needs to be relative to the size of the "stick"ed item
if (windowpos >= pos.top) { s.addClass("stick"); $("body").css("margin-top", 60); } else { s.removeClass("stick"); $("body").css("margin-top", 0); }
});
});
As comments,
$("body").css("margin-top", s.height());
Gives a dynamic margin-top css value to the <body> based on the height on the element ( #picture1 ) that is being fixed during window.scroll
As an addition, you mention that the height may change on screen resize ( rwd )
So this may be good to add also ( to keep it in check )
$(window).resize(function() {
var s = $("#picture1");
if(s.hasClass("stick") {
$("body").css("margin-top", s.height());
}
});

Jquery when the user hits bottom of the page

I've been working on a scroll to top function for my website, and that part of it works fine. My problem is however that I have a fixed div that is overlapping my footer when it hits the bottom of the page.
Here is the function that I have working.
$(document).scroll(function (e) {
if (document.body.scrollTop >= 800) {
$('#beamUp').show(1000);
} else {
$('#beamUp').hide(1000);
return false;
}
});
Is there somehow I could detect when I hit that part of the page and stop the div from moving past that.Help is much appreciated!
jsFiddle: http://jsfiddle.net/zazvorniki/RTDpw/
Just get the height of the page, minus the height of the div in question, as well as the footer... make sure the top is never greater than that value... you'll also need an onresize event handler re-evaluate that value.
looking at your jsfiddle... here are my edits
In your scroll listener, I am checking for the position of the page, and adjusting the bottom position of the floater appropriately. I also set the initial display:none, so you don't need to call .hide() in your initial script. In addition, resizing the window has the effect of scrolling for your use, so I changed the listener for both events.
$(document).on('scroll resize', function (e) {
var viewHeight = $(window).height();
var viewTop = $(window).scrollTop();
var footerTop = $("footer").offset().top;
var baseline = (viewHeight + viewTop) - footerTop;
var bu = $("#beamUp").css({bottom: (baseline < 0 ? 0 : baseline) + 'px'});
if (viewTop >= 50) {
bu.show(1000);
} else {
bu.hide(1000);
}
});

Categories

Resources