Keep a div visible when content would push it down - javascript

I want to have a div positioned in the bottom of another div. This i can solve with just
bottom: 0px;
postion: fixed;
But, if the containing div is larger than the window, i want to freeze the inner div to the bottom of the window.
If it's easier the first condition can be scrapped and the inner div can just be positioned under the content, the important part is that the content must always be visible.

The best solution would be to detect with JavaScript if the footer is visible inside the viewport. If not, you should change it's styles to stick to the bottom of the window instead of that of the containing div.
You could use this function to see if it's in the viewport:
function elementInViewport(el) {
var top = el.offsetTop;
var left = el.offsetLeft;
var width = el.offsetWidth;
var height = el.offsetHeight;
while(el.offsetParent) {
el = el.offsetParent;
top += el.offsetTop;
left += el.offsetLeft;
}
return (
top >= window.pageYOffset &&
left >= window.pageXOffset &&
(top + height) <= (window.pageYOffset + window.innerHeight) &&
(left + width) <= (window.pageXOffset + window.innerWidth)
);
}
(taken from How to tell if a DOM element is visible in the current viewport?)
Now, every time you scroll or resize the page you can do a check that runs that function. Based on that, you can decide to set a class or change a CSS property that will do what you're looking for.
Since you didn't include any code (in the future, please do) I'm going to assume your code looks something like this:
<div class="wrapper">
(contents)
<div class="footer">footer</div>
</div>
To stick the .footer to the bottom of .wrapper, it has to have a 'positon: absolute' and the wrapper will need a position: relative. However, if you change it's position property to fixed and the wrapper to static (the default for all elements), the footer is going to stick to the bottom of the window instead.
View this example http://jsfiddle.net/GMYEh/
Now, using the script above you can tell which of the two it should be. You have to use a fake element at the same position of the footer, instead of the footer itself. That way, if you move the footer to the bottom of the window, you can still measure whether or not the bottom of the wrapper is in the viewport. (If you measure the footer itself and move it you'll get stuck).
The script that does this (in jQuery):
// add a fake footer after the wrapper
$('.wrapper').after($('<div class="fakefooter" />'));
$(document).on('resize scroll', function(e){
//measure if the fake footer is in viewport
if(elementInViewport($('.fakefooter')[0])) {
// If so, it should be in the bottom of the wrapper.
$('.wrapper').css('position', 'relative');
$('.footer').css('position', 'absolute');
} else {
// else it should be in the bottom of the window
$('.wrapper').css('position', 'static');
$('.footer').css('position', 'fixed');
}
});
Working example:
http://jsfiddle.net/GMYEh/4/

Try this:
HTML:
<div id="wrapper">
<div id="innerContent"></div>
</div>
CSS:
.fixedContent {
position: fixed;
bottom: 0;
}
and the javascript:
var wrapper = document.getElementById('wrapper');
var content = document.getElementById('innerContent');
function position() {
if (wrapper.offsetHeight + wrapper.offsetTop - content.offsetHeight - window.scrollY > window.innerHeight) {
content.className += ' fixedContent';
} else {
content.className = content.className.replace('fixedContent', '');
}
}
window.onload = position;
window.onresize = position;
If you're open to jQuery you can make the javascript more simple and compatible
var $wrapper = $('#wrapper');
var $content = $('#innerContent');
$(window).on('load resize', function() {
$content.toggleClass('fixedContent', $wrapper.outerHeight(true) $content.offset().top - $content.outerHeight(true) - $(document).scrollTop() > $(window).height());
});
EDIT:
I modified the conditions a bit adding the vertical scroll value and top offset.

Related

Changing div position to fixed with javascript attaches the div to document not viewport

I am looking for a way to determine if any part of a div is touching the top of the viewport and fix an item in that div to the top of the viewport using vanilla javascript.
I have been able to sort out how to determine if the div is touching the top of the viewport and trigger changes to the div's style. But for some reason when I change the div's position: absolute to position: fixed the div fixes to the top of the document, not to the top of the viewport, hence is not visible.
My js
function touchTop() {
var div = $('itin');
var rect = div.getBoundingClientRect();
var y = rect.top;
var h = rect.bottom;
if ((y < 0) && (h > 0)) {
document.getElementById('seemore').style.position = 'fixed';
document.getElementById('seemore').style.top = '45%';
} else {
document.getElementById('seemore').style.position = 'absolute';
document.getElementById('seemore').style.top = '66px';
}
}
window.addEventListener('scroll', touchTop);
The basic div HTML
<div id="itin" class="container">
<div class="sp20"></div>
<div class="text rgt">
<h3>your daily adventures</h3>
<p>blah blah blah</p>
</div>
<div id="seemore" class="ghstbtn">See More</div>
</div>
And the basic initial CSS
#seemore {
width: auto;
position: absolute;
top: 66px;
right: 20px;
}
To clarify further: My problem that needs solving is that when javascript changes the style.position to fixed the #seemore div gets positioned such that the 'top' value is measured from the top of the document, not from the top of the viewport. So basically not visible in the viewport.
If I understand you correctly, I think your problem lays here:
if ((y < 0) && (h > 0))
When the container div hits the top of the document, position to "seemore" is set to fixed, but as fast as the bottom of the div hits the top of the document,
"h === 0" and the position is again set to absolute.
Try this.
const seeMore = document.getElementById('seemore');
const div = document.getElementById('itin');
window.addEventListener('scroll', checkBoundries);
function checkBoundries() {
var rect = div.getBoundingClientRect();
var y = rect.top;
var h = rect.bottom;
if (y < 0) {
seeMore.style.position = 'fixed';
seeMore.style.top = '45%';
} else {
seeMore.style.position = 'absolute';
seeMore.style.top = '66px';
}
}
Turns out to be related to a filter applied to a parent of a parent of a parent of a ....
Found some old questions regarding issues with transformations and position:fixed dating back some 5 to 7 years ago. And even though many mentioned filing issue reports with the browser makers, it seems the problem has never been addressed and resolved. One comment mentioned filters could also cause the issue.
Moved the filter to a separate class which is now added and removed, rather than applying the filter directly to the div. And everything works as expected.

Finding position of element within scrollable div

I have these "pages" aka div's inside a scrollable container. On command, I am trying to find out what part of the div in question, is touching the top of .pageContent.
So for example, right when the page loads, no part of #page_1 is touching the top of pageContent, but as I scroll down. #page_1 hits the top of .pageContent and I now want to figure out where that is.
I know I can get the position of .pageContent using $("#pageContent").scrollTop() but these page's could be different sizes and I am not sure how to go about figuring it out.
Could anyone put me in the right direction?
jsfiddle
HTML
<div id="pageContent">
<div id="page_1" class="content"></div>
<div id="page_2" class="content"></div>
<div id="page_3" class="content"></div>
</div>
CSS
#pageContent {
overflow: auto;
width:500px;
height:300px;
padding:10px;
border:1px solid black;
background-color:grey;
}
.content {
height:400px;
width:300px;
margin:0 auto;
background-color:red;
margin-bottom:10px;
}
You can use the jQuery .position() function to compute where each page is in relation to the top of the container. See this Fiddle.
For example, for #page_1,
var page1 = $('#page_1');
$('#pageContent').scroll(function() {
// page1.position().top gives the position of page_1 relative to the
// top of #pageContent
});
ScrollTop can be used, be I wouldn't recommend it.
Attach a scroll event to your main div and listener for all the objects inside:
$('#pageContent').scroll(function(){
var pages = $("#pageContent > .content");
for (var i = 0; i < pages.length; i++)
{
if ($(pages[i]).position().top < 0 && ( $(pages[i]).position().top + $(pages[i]).outerHeight() ) > 0)
{
var outerHeight = $(pages[i]).outerHeight();
var pixels = (outerHeight - (outerHeight + $(pages[i]).position().top));
console.log("These pixels are in view between: " + pixels + " and " + outerHeight );
}
}
})
Every time the div scroll a loop is performed checking the position of all elements. If the elements scroll out of view a the top the if is triggered, calculating the remaining visible pixels of the page currently visible.
This uses jQuery's: position() and outerHeight() and JavaScript's native offsetTop.
http://jsfiddle.net/q5aaLo9L/4/
I tried something like this
$(document).ready(function () {
var divs = $('.content').map(function (i, el) {
return $(el).offset().top - $(el).parent().offset().top;
});
$('#pageContent').scroll(function () {
var index = findIndex($(this).scrollTop(), divs) - 1;
if (index > -1) {
console.log($(this).children().eq(index).attr('id'));
} else {
console.log('outside');
}
});
});
function findIndex(pos, divs) {
return (divs.filter(function (el, et) {
return et <= pos
}).length);
}
It's not super clean code because I had to do it quickly.
DEMO
I hope this helps
I mocked this up, it uses JQuery's each() function to iterate through the pages and return the information of the page that has breached the top of the box.
I wasn't sure from your question exactly what you wanted returned, so I got it to return either the percentage of the page that has cleared the top border, the position (as negative value of pixels) of the top of the "page " in relation to the content container, and also just the ID of that div.
var getCurrentPage = function(){
var page;
var position;
var percentageRead;
$('.content').each(function(){
if($(this).position().top <= 0){
page = $(this);
position = $(this).position().top;
}
});
percentageRead = ((position *-1)/ $(page).height()* 100);
console.log(page.attr('id'));
console.log(position);
console.log(percentageRead + '%');
}
$('#pageContent').on('scroll', getCurrentPage);
You could fire this on any event but I used scroll to build it.

Scrolling Two Divs Using JQuery/Javascript

Wrapper - Overflow Hidden
Div One: Sidebar
Div Two: Main Content
Div Two will have a normal scroll. Div One I wish to have no visible scroll however when you scroll Div One it scrolls Div Two.
Upon Div One's height hitting the bottom, it will no longer scroll and visa-versa for scrolling back up.
This will result in the sidebar always being visible at the side. Before you ask, I've tried all positioning types to get this to work resulting in many failed attempts.
My live demo can be seen here: http://rafflebananza.com/admin/newadmin.html#
Note I've tried to make a JSFiddle simplified but my maths does not seem to work in there the same. Please suggest whether I should fork all my page to there or whatnot for future visitors needing the same help.
Overview
Scrolling in the wrapper will scroll sidebar to point x only (x being the sidebars height) then stopping but will continue to allow the content to be scrolled. Visa-versa for scrolling back up.
Somewhat half way there...
var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop,
position = document.body.scrollTop;
function scrollD() {
var scroll = document.body.scrollTop;
if (scroll > position) {
// Scrolling Down Functions
} else {
// Scrolling Up Functions
}
position = scroll;
}
Updated the answer to match OPs requirements.
I downloaded your website in its current state and made the following changes to your code:
var scrollY = 0;
$(window).scroll(function() {
var sideNav = $('.SideNav'); // The side navigation
var wScrollY = $(this).scrollTop(); // Current scroll position of Window
var navHeight = sideNav.height(); // Height of the Navigation
var StageHeight = $(window).height() - 46; // The display space
if(sideNav.height() > StageHeight) { // Do the following if the side navigation is higher than the display space
var spaceLeft = sideNav.height() - StageHeight; // spaceLeft -> how many pixel left before fixing navigation when scrolling
if(scrollY < wScrollY) { // Scroll direction is down
if (wScrollY >= spaceLeft) // If scroll top > space left -> fixate navigation at the bottom, otherwise scroll with the content
sideNav.css({top:46-spaceLeft+wScrollY});
if (wScrollY <= 46) // Set top strict to 46. Sometimes there is white space left, caused by the scroll event.
sideNav.css({top:46});
} else { // Scroll direction is up
var sideNavTop;
if (sideNav.offset().top < 0) {
sideNavTop = Math.pow(sideNav.offset().top); // if top is negative, make it positive for comparison
} else {
sideNavTop = sideNav.offset().top;
}
if (sideNavTop > (46+wScrollY)) // Fixate the header if top of navigation appears
sideNav.css({top:46+wScrollY});
}
} else {
sideNav.css({top:46+wScrollY}); // Fixate always
}
scrollY = wScrollY;
});
This will let you scroll your side navigation up until its end. Then fixate. If you scroll up, it will still be fixated until your reach the point, where the navigation must scrolled back to its original position.
You can check the edited version here: http://pastebin.com/Zkx4pSKe
Just copy the raw code into a blank html page and try it out.
It's a bit messy and maybe not the best solution, but it works.
Ok, here you go:
var $sidebar = $('.sidebar'),
$window = $(window),
previousScroll = 0;
$window.on('scroll', function (e) {
if ($window.scrollTop() - previousScroll > 0) {
$sidebar.css({
'top': Math.max($window.scrollTop() + $window.height() - $sidebar.outerHeight(true), parseInt($sidebar.css('top'))) + 'px'
});
} else {
$sidebar.css({
'top': Math.min($window.scrollTop(), parseInt($sidebar.css('top'))) + 'px'
});
}
previousScroll = $window.scrollTop();
});
http://jsfiddle.net/7nwzcpqk/1/
i might have misunderstood your desired result incorrectly but you can see if this works for you :
.SideNav {
position: fixed; // you currently have this as position:absolute;
}
You don't need nor a wrapper element nor jQuery. I assume that you are using a wrapper because you want to have the top bar placed there. I think there is a better way to do it by using simply three divs.
The top bar has to be fixed (to be always visible) and of full width.
The side bar also has to be fixed (to be always visible) with a top margin of the height of the top bar.
The content needs just a left padding (width of side bar) and top padding (height of top bar).
Here is the example code (http://jsfiddle.net/zckfwL4p/):
HTML
<div id="top_bar"></div>
<div id="side_bar">links here</div>
<div id="content"></div>
CSS
body {
margin:0px;
padding:0px;
}
#side_bar {
width:50px;
position: fixed;
left:0px;
top:20px;
background-color:blue;
}
#top_bar {
position:fixed;
height:20px;
left:0px;
right:0px;
background-color:red;
}
#content {
position:relative;
padding-left:55px;
padding-top:25px;
}

stick div to screen if bottom of div and screen matches

Hello all I am working on a project where in a page I have to stick the div to screen (disable scrolling) when its bottom is at the bottom of screen. I have two divs in the page and both the divs are of variable height. I want to stick the div2 and scroll the div1.
<script>
var divheight
var scrolltop
var screenheight
if(divheight-scrolltop <= screenheight){
/* now stick the div wherever it is i can not
use fixed position as both the divs are floating and
fixing the position will make it to change the position*/ }
else { /*un stick the div*/ }
</script>
i dont know what to put in if and else please help me
Make a function which fire on scroll. The main aim of the function would be to see the difference between screen height and bottom of the div. Once the difference is less than or equal to zero modify the css position to fixed. This will help you
(function ($) {
$('.DIV1').scroll(function () {
var $this = $(this),
win_ht = $(window).height(),
div_ht = $this.height(),
div_bot = $this.offset().top + div_ht;
if (win_ht - div_bot <= 0) {
$this.css({
'position': 'fixed',
'bottom': '0'
})
}
});
})(jQuery);

Javascript: have div always remain at the top when it reaches the top edge of browser with jquery

how to have a div that always stay on the screen? Lets say i have a div at the left hand site. When the browser is scroll to the bottom, the div will remain there ONLY when its' top reaches the top edge of browser screen so that it will not be hidden. I am using jquery too.
Thank you.
here is a Good ScreenCast By RemySharp Regarding this Issue
http://jqueryfordesigners.com/fixed-floating-elements/
Demo Page :
http://static.jqueryfordesigners.com/demo/fixedfloat.html
You need to invoke .scrollTop() on the window and compare that with the offset top value from that DIV.
$(window).bind('scroll', function(e){
var $div = $('.top').
sTop = $(window).scrollTop();
if($div.offset().top <= sTop)
$div.css('top', sTop);
else
$div.css('top', '100px');
});
Whereas in this example, .top is the element which should stay at top.
Example: http://www.jsfiddle.net/2C6fB/8/
If you want it to always stay in thesame place, you can use the css property position: fixed; else you can use a combination of $(window).scroll() and .scrollTop(); to detect where your div is in relation to the screen and apply the right positioning.
/* PlugTrade.com - Sticky Top jQuery Plugin */
jQuery.fn.sticky_top = function () {
/* check for our hidden div.. create it if it doesn't exist */
if (!this.find("#sticky_top").length > 0)
this.append("<div id='sticky_top' style='display:none'>"+this.css('top')+"</div>");
var thisdiv = this;
$(window).bind('scroll', function(e){
var initval = thisdiv.find("#sticky_top").text();
var wintop = $(window).scrollTop();
var boxtop = initval.replace(/px/i, "");
if(wintop >= boxtop)
{
if ( $.browser.msie )
{
thisdiv.css('top', wintop+'px');
} else {
thisdiv.css('position', 'fixed');
thisdiv.css('top', '0');
}
// console.log(boxtop+':'+wintop);
/* thisdiv.css('top', wintop+'px'); */
}
else
{
thisdiv.css('position', 'absolute');
thisdiv.css('top', initval);
}
});
}
You can use like this:
$('#div1').sticky_top();
Keep your div position: fixed;

Categories

Resources