Make a fixed div stay fixed horizontally - javascript

Here is code that fixes a div to the top of the screen when the user scrolls to it.
However, on my browsers, if the user scrolls left or right, the bar stays fixed to the top but scrolls along. I wanted the bar to stay put, with the content it's over.
Here is the jfidddle
Here is the code:
$(function(){
// Check the initial Poistion of the Sticky Header
var stickyHeaderTop = $('#stickyheader').offset().top;
$(window).scroll(function(){
if( $(window).scrollTop() > stickyHeaderTop ) {
$('#stickyheader').css({position: 'fixed', top: '0px'});
$('#stickyalias').css('display', 'block');
} else {
$('#stickyheader').css({position: 'static', top: '0px'});
$('#stickyalias').css('display', 'none');
}
});
});

The key part is left:-$(window).scrollLeft()
DEMO
$(function () {
// Check the initial Poistion of the Sticky Header
var stickyHeaderTop = $('#stickyheader').offset().top;
$(window).scroll(function () {
if ($(window).scrollTop() > stickyHeaderTop) {
$('#stickyheader').css({
position: 'fixed',
top: '0px',
left: -$(window).scrollLeft()
});
$('#stickyalias').css('display', 'block');
} else {
$('#stickyheader').css({
position: 'static',
top: '0px'
});
$('#stickyalias').css('display', 'none');
}
});
});

Related

Navigation bar not resizing to browser screen

Here's the link to my code:
https://jsfiddle.net/81scw7eg/
MY JavaScript:
$(function() {
/* Stick the #bottomMenuBarContent to the top of the window */
var nav = $('#bottomMenuBarContent');
var navHomeY = nav.offset().top;
var isFixed = false;
var $w = $(window);
$w.scroll(function() {
var scrollTop = $w.scrollTop();
var shouldBeFixed = scrollTop > navHomeY;
if (shouldBeFixed && !isFixed) {
nav.css( {
position: 'fixed',
top: 0,
left: nav.offset().left,
width: nav.width()
});
isFixed = true;
} else if (!shouldBeFixed && isFixed) {
nav.css({
position: 'static'
});
isFixed = false;
}
});
});
/* Changes Navigation Bar Color on Scroll */
$(document).ready(function(){
var scroll_pos = 0;
$(document).scroll(function() {
scroll_pos = $(this).scrollTop();
if (scroll_pos > 50) {
$("#bottomMenuBarContent").css('background-color', '#2a2a2a');
} else {
$("#bottomMenuBarContent").css('background-color', 'grey');
}
});
});
I don't know why, but my navigation bar isn't resizing to my screen. Try opening up my site and resizing it to a smaller size. Now scroll down on the website so that the navigation bar changes colors, and then maximize the browser screen. For some reason it doesn't move along with it. Any ideas why?
Example Screenshot
in your example you set the width of the element to it's original width
(which is in this case made by it's content and which doesn't go 100% of the screen the moment you switch from position: static to position: fixed)
just replace the line
width: nav.width()
with
right: 0

Google pubads appear and then disappear

I'm using Google pubads on http://development-client-server.com/ds/ which is working great, until you get to the actual story page (see http://development-client-server.com/ds/speech-more-common-autism/), when the right top sidebar ad will load and then disappear quickly.
I've narrowed it down to the stickySidebars function I'm using to stick both the social media bar on the left and the jobs listing div on the right (beneath where the Google ad is). However, the sticky function shouldn't affect the Google ad at all?
Here's the JS function I'm using, which I've already rewritten several times (and have tried to talk the clients out of using already).
<script>
// Sticky Sidebars
function stickySidebars() {
var length = $('.post-content').height() - $('article .sharing-links').height() + $('.post-content').offset().top;
var lengthSidebar = $('.sticky-container').height() - $('aside .job-listings').height() + $('.sticky-container').offset().top -30;
$(window).scroll(function () {
// Sharing Links
var scroll = $(this).scrollTop() + 90;
var height = $('article .sharing-links').height() + 'px';
if (scroll < $('.post-content').offset().top) {
$('article .sharing-links').css({
'position': 'absolute',
'top': 'auto',
'bottom': 'auto'
});
} else if (scroll > length) {
$('article .sharing-links').css({
'position': 'absolute',
'bottom': '0',
'top': 'auto'
});
} else {
$('article .sharing-links').css({
'position': 'fixed',
'top': '90px',
'height': height
});
}
// Sidebar
var heightSidebar = $('aside .job-listings').height() + 'px';
if (scroll < $('aside .job-listings').offset().top) {
$('aside .job-listings').css({
'position': 'absolute',
'top': '300px',
'bottom': 'auto'
});
} else if (scroll > lengthSidebar) {
$('aside .job-listings').css({
'position': 'absolute',
'bottom': '30px',
'top': 'auto'
});
} else {
if (scroll < $('.sticky-container').offset().top + 300) {
$('aside .job-listings').css({
'position': 'absolute',
'top': '300px',
'bottom': 'auto'
});
} else {
$('aside .job-listings').css({
'position': 'fixed',
'top': '90px',
'height': heightSidebar
});
}
}
});
}
$(window).on('load',function(){
if($(window).width() > 1100){
stickySidebars();
}
});
$(window).resize(function() {
if($(window).width() > 1100){
stickySidebars();
}
});
</script>
The issue is not caused by the sticky sidebar. It is caused by this bit of code:
$(window).on('load',function(){
// Other unrelated functions here...
/*****************************/
// Move Sidebar in Mobile
/*****************************/
if($(window).width() <= 980){
$("aside").appendTo(".mobile-sidebar");
} else {
$("aside").insertAfter(".single-article article");
}
});
Essentially the ad loads and then you move the container (the aside), which causes the ad to disappear.
There are a few different options, but essentially you either need the Google ad script to run after that piece of code or you need to refresh the ads. To refresh the ads you should be able to run this line of code straight after your if else statement:
googletag.pubads().refresh()
This refreshes all of the ads. Depending on how you have it setup you can pass in a variable to refresh() so that a specific ad is refreshed e.g.
var slot1 = googletag.pubads().display('/1234567/sports', [728, 90], 'div-1');
googletag.pubads().refresh([slot1]);
Google Reference Docs for refresh()

stick part in a specific range

i have a container that is stick to top after a specific point.
but its not enough for me.
i have a footer in the page and when the screen is small the stick part is hiding under the footer.
i want it to stop moving down in the footer top (to stop be fixed to 0 that point but be fixed to minus number that is the substraction between them).
this is my code.
what should i add for that goal?
and when to call it?
on resize?
on ready?
etc.
thanks a lot
window.onscroll = function (event) {
fixDiv();
};
function fixDiv() {
if (getBrowserHeight().width > 1284) {
var $div = $("#Container");
if ($(window).scrollTop() > $div.data("top")) {
$('#Container').css({ 'position': 'fixed', 'top': '0' });
}
else {
$('#Container').css({ 'position': 'static', 'top': 'auto' });
}
}
}
$(document).ready(function () {
$("#Container").data("top", $("#Container").offset().top);
});
This should get you going.
Don't mind to ask for help if somehting isn't clear.
$(document).ready(function() {
$(window).scroll(function() {
var footerEl = $('footer').offset().top;
var footerTop = (footerEl - $(window).scrollTop());
var containerHeight = $('.container').height();
var footerHeight = $('footer').height();
console.log('footer', footerTop);
$('.container').removeClass('sticky');
if (footerTop <= containerHeight) {
$('.container').addClass('sticky');
$('.container').css('bottom', footerHeight);
}
});
});
body {
height: 1000px;
position: relative;
}
.container {
width: 100%;
min-height: 300px;
position: fixed;
top: 0;
background: red;
}
.sticky {
position: absolute;
top: auto;
}
footer {
width: 100%;
min-height: 500px;
position: absolute;
bottom: 0;
background: black;
}
<html>
<body>
<div class="container"></div>
<footer></footer>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
</html>
I've tried to make as few changes to your code as possible, but there's better ways to get around this ie. using classes, like in #mhx answer. Full JavaScript below (sorry, had to remove your getBrowserHeight() as it wasn't defined):
window.onscroll = function (event) {
fixDiv();
};
function fixDiv() {
var $div = $("#Container");
var $footer = $("footer");
if ($(window).scrollTop() >= $div.data("top") && $(window).scrollTop() < $footer.data("top") - $div.height()) {
$('#Container').css({ 'position': 'fixed', 'top': '0' });
}
else if ($footer.data("top") > $footer.data("top") - $div.height()) {
$('#Container').css({ 'position': 'absolute', 'top': $footer.data("top") - $div.height() });
}
else {
$('#Container').css({ 'position': 'static', 'top': 'auto' });
}
}
$(document).ready(function () {
$("#Container").data("top", $("#Container").offset().top);
$("footer").data("top", $("footer").offset().top);
});
Besides adding a top data attribute to your footer and defining $footer in the start of fixDiv(),I've added this to your initial if statement, to make sure that the scroll position, does not exceed the top of the footer minus the height of your div.
&& $(window).scrollTop() < $footer.data("top") - $div.height()
... and I've added this else if statement, in case it does exceed the top of the footer minus the height of your div
else if ($footer.data("top") > $footer.data("top") - $div.height()) {
$('#Container').css({ 'position': 'absolute', 'top': $footer.data("top") - $div.height() });
}
Here's a fiddle: http://jsfiddle.net/ds5tptay/

stick child to bottom when parent div touches the browser bottom

I want to stick child div to bottom when parent div touches the browser bottom.
P.S : This should happen when the parent div is pushed down not when scrolled down.
For example in my demo there is a content panel which is hidden. If you click on expand link you get to see the expanded content (which is pushing the bottom_content div to the bottom).
But accordion is just an example, there will be some other element which will be pushing the bottom_content div down. So I dont want to write stick function with reference to accordion.
It should stick down only when bottom_content div touches the bottom of the browser and when there is no much content in the page then the child div should stay as it is like child of the bottom_content
Parent div: bottom_content
Child div: footer
Here is my code currently used, which is not proper
$('.expandble_conetnt a').click(function(event){
event.preventDefault();
$(this).next('span').slideToggle();
});
//this is for stick to the bottom
var stickyHeaderbottom = $('.footer').offset().top;
$(window).scroll(function () {
if ($(window).scrollTop() > stickyHeaderbottom) {
$('.footer').css({ position: 'fixed', bottom: '0px', width: '95%', left: '2.5%' });
} else {
$('.footer').css({ position: 'static', bottom: '0px', width: '100%' });
}
});
DEMO
The whole idea is to handle .footer position on window scrolling, on window resizing and after .slideToggle() for the list is completed:
Fiddle.
var stickyHeaderbottom = $('.footer').offset().top;
$('.expandble_conetnt a').click(function()
{
$(this).next('span').slideToggle(function()
{
handleBottom();
});
return false;
});
$(window).scroll(function()
{
handleBottom();
});
$(window).resize(function()
{
handleBottom();
});
function handleBottom()
{
if ($(window).height() + $(window).scrollTop() < $(document).height())
{
$('.footer').css({ position: 'fixed', bottom: '0', width: '95%', left: '2.5%' });
}
else
{
$('.footer').css({ position: 'absolute', bottom: '0', width: '100%', left: 0 });
}
}
Edit. Updated fiddle without weird footer jumping after list opening.
var stickyHeaderbottom = $('.footer').offset().top;
$('.expandble_conetnt a').click(function()
{
var toggledElement = $(this).next('span');
handleBottom(toggledElement.height());
toggledElement.slideToggle(function()
{
handleBottom();
});
return false;
});
$(window).scroll(function()
{
handleBottom();
});
$(window).resize(function()
{
handleBottom();
});
function handleBottom(additionalHeight)
{
var pageHeight = $(document).height();
if (additionalHeight)
{
pageHeight += additionalHeight;
}
if ($(window).height() + $(window).scrollTop() < pageHeight)
{
$('.footer').css({ position: 'fixed', bottom: '0', width: '95%', left: '2.5%' });
}
else
{
$('.footer').css({ position: 'absolute', bottom: '0', width: '100%', left: 0 });
}
}
you can make js on.change to change that div position to absolute and bottom:0 left:0

making a div stick to the top of the screen but if scrolled back up, return to it's original position?

This will make a div that is position: absolute ( top: 46px ) on a page become fixed to the top of the page ( top: 0px ) when scrolled to a certain point ( the distance from the div to the top of the page )
$(window).scroll(function (e) {
$el = $('#sticky');
if ($(this).scrollTop() > 46 && $el.css('position') != 'fixed') {
$('#sticky').css({
'position': 'fixed',
'top': '0px'
});
}
});
BUT it doesn't reset the position of the div when you're back at the top of the page, and I want it to. Any suggestions? Also I want to make sure this is the best way to do this — if there's a css only, non-javascript solution I'm all ears.
I would recommend either keeping the sticky content fixed or absolute, but not switching between the two.
Fixed: http://jsfiddle.net/CpM8H/2/
$(window).scroll(function (e) {
$scrollTopDiff = 46 - $(this).scrollTop();
$('#sticky').css({
'top': ( $scrollTopDiff > 0 ? $scrollTopDiff : 0 ) + 'px'
});
});
Absolute: http://jsfiddle.net/CpM8H/3/
$(window).scroll(function (e) {
$scrollTop = $(this).scrollTop();
$('#sticky').css({
'top': ( $scrollTop > 46 ? $scrollTop : 46 ) + 'px'
});
});
If you really need to switch between fixed and absolute, here is my first though on how to do that, but the sticky content may jump around a bit:
$(window).scroll(function (e) {
$el = $('#sticky');
if ($(this).scrollTop() > 46 ) {
$el.css({
'position': 'fixed',
'top': '0px'
});
} else {
$el.css({
'position': 'absolute',
'top': '46px'
});
}
});

Categories

Resources