Change position of div based on content & viewport height using jquery - javascript

I want to have a div be fixed at the bottom of the window when the window is taller than the content height. If the content height is taller than the window height, I want the div position to remain relative.
I currently have this mostly working, however I don't want the div to overlap the content at all. I tried various forms of below, but still not working:
var body = content+bottomBar
if (body > viewport) {
$(".bottom-bar").css({
'position':'relative'
});
} else {
$(".bottom-bar").css({
'position': 'fixed'
})
}
I also am having trouble getting the window.resize to work.
Any help would be appreciated!
http://jsfiddle.net/no05x1vx/1/

Referring to the jsfiddle linked by the OP, here are a few changes to make the code work as expected, please see the comments:
var content = $(".content").height()
var viewport = $(window).height();
// Use innerHeight here as the bottom-bar div has height 0 and padding 60px
// .height() would return 0
var bottomBar = $(".bottom-bar").innerHeight();
var body = parseInt(content)+parseInt(bottomBar)
$(window).on('resize', function(){
// Get new viewport height
viewport = $(window).height();
if (content > (viewport-bottomBar) ) {
$(".bottom-bar").css({
'position':'relative'
});
} else {
$(".bottom-bar").css({
'position': 'fixed'
})
}
});
// Trigger resize after page load (to avoid repeated code)
$(document).ready(function(){
$(window).resize();
});

Related

How can I fix a div under my original header if it changes height when scrolling?

I created an additional menu bar (.secondnav) that I want to place right below the original header (#headAnnouncementWrapper) in a website. The problem is, when scrolling, the header's height changes when going from relative position to fixed at the top, and also when on mobile.
I've been trying with this:
var scrolled = 78;
var headHeight = $('#headerAnnouncementWrapper').height();
$(window).scroll(function() {
if ($(window).scrollTop() > scrolled) {
$('.secondnav').css('position', 'fixed');
$('.secondnav').css('top', headHeight);
} else {
$('.secondnav').css('position', 'relative'),
$('.secondnav').css('top', headHeight);
}
});
But I don't know how I should be calculating the headHeight variable so it changes when the height changes, and how to use that result as the top value for the .secondnav's css.
Check the height of the main header inside the scroll event. Each time the scroll event triggers, it will recheck the height. Then, the next line will adjust the top margin of the lower header to match the height of the upper header. Top-margin here replaces your position method.
var scrolled = 78;
$(window).scroll(function() {
var headHeight = $('#headerAnnouncementWrapper').height();
$('.secondnav').css('marginTop', headHeight);
if ($(window).scrollTop() > scrolled) {
$('.secondnav').css('position', 'fixed');
} else {
$('.secondnav').css('position', 'relative'),
}
});

Determine element is at bottom of viewport and add class to it?

need some help here. I need to determine when a certain element is at bottom position of the viewport and then to add fixed class to it. So on scroll down add class when element is at bottom 0 and remove class when i scroll back up.
$(window).scroll(function() {
var $el = $('.content-btn-row');
if ($($el).position().top + $($el).height()) {
console.log("bottom!");
$(".content-btn-row").addClass("fixed");
} else {
$(".scontent-btn-row").removeClass("fixed");
}
});
IMO we should take into account inner height of a window's content area (it can be different that window height) and check if document has been scrolled.
window.innerHeight - returns the inner height of a window's content area
window.pageYOffset - returns the pixels the current document has been scrolled (vertically) from the upper left corner of the window
If the element is below viewport at the beginning this code should be ok:
var elem = window.innerHeight + $($el).height(); //position of the element
var winScroll = window.innerHeight + window.pageYOffset; //viewport height + scroll
if (elem) >= (winScroll) {
console.log("bottom!");
$(".content-btn-row").addClass("fixed");
} else {
$(".scontent-btn-row").removeClass("fixed");
}
}
and it will be better to check if there is a class "fixed" with hasClass before we add or remove it.
Why are you comparing the variables by adding same constant values(window.innerHeight) to them?
var elem = $($el).height();
var winScroll = window.pageYOffset;
if (elem) >= (winScroll) {
console.log("bottom!");
$(".content-btn-row").addClass("fixed");
} else {
$(".scontent-btn-row").removeClass("fixed");
}}
By this way we can reduce some complexity and code

Calculating pixels from bottom of element

I'm trying to create a scroller which loads content when the user nears the bottom of an element however I'm struggling with calculating the current distance from the bottom of the element #grid when the user scrolls.
$(window).scroll(function (event) {
var scroll = $(window).scrollTop();
var div = $('#grid');
var bottom = ((div.offset().top + div.height()) - scroll);
$('.scroll').html(bottom);
});
The .scroll element displays the value although it doesn't seem to be giving correct numbers. Any ideas, I've come to a stand still. I seem to be getting the distance from the top of the window to the bottom of the container, not from the current scroll position?
Top of page
Scrolled down
You need to add the height of the window too.
$(window).scroll(function (event) {
var scrollBottom = $(window).scrollTop() + $(window).height();
var div = $('#grid');
var bottom = ((div.offset().top + div.height()) - scrollBottom);
$('.scroll').html(bottom);
});
If bottom is negative by less than the window height, then the bottom of the #grid div is visible on the screen.

Jquery animate negative top and back to 0 - starts messing up after 3rd click

The site in question is this one:
http://www.pickmixmagazine.com/wordpress/
When you click on one of the posts (any of the boxes) an iframe will slide down from the top with the content in it. Once the "Home" button in the top left hand corner of the iframe is clicked, the iframe slides back up. This works perfectly the first 2 times, on the 3rd click on of a post, the content will slide down, but when the home button is clicked, the content slides back up normally but once it has slid all the way up to the position it should be in, the iframe drops straight back down to where it was before the home button was clicked, I click it again and then it works.
Here is the code I've used for both sliding up and sliding down functions:
/* slide down function */
var $div = $('iframe.primary');
var height = $div.height();
var width = parseInt($div.width());
$div.css({ height : height });
$div.css('top', -($div.width()));
$('.post').click(function () {
$('iframe.primary').load(function(){
$div.animate({ top: 0 }, { duration: 1000 });
})
return false;
});
/* slide Up function */
var elm = parent.document.getElementsByTagName('iframe')[0];
var jelm = $(elm);//convert to jQuery Element
var htmlElm = jelm[0];//convert to HTML Element
$('.homebtn').click(function(){
$(elm).animate({ top: -height }, { duration: 1000 });
return false;
})
Have you considered using Ajax, like load(), ready() in jquery to control them better?
I am also not sure what you are trying to do with this.
var height = $div.height();
$div.css({ height : height });
may be you want to get the height of the current window? Where you can get it this way
var $dDiv = $('iframe.primary');
var innerH = window.innerHeight;
$dDiv.height(innerH);
Also try avoiding naming your custom var with default names like height, width, div, etc... You will confuse yourself and make debugging a pain.

How to reliably get screen width WITH the scrollbar

Is there a way to reliably tell a browser's viewport width that includes the scrollbar, but not the rest of browser window)?
None of the properties listed here tell me the width of the screen INCLUDING the scrollbar (if present)
I figured out how to accurately get the viewport width WITH the scrollbar using some code from: http://andylangton.co.uk/blog/development/get-viewport-size-width-and-height-javascript
Put this inside your $(document).ready(function()
$(document).ready(function(){
$(window).on("resize", function(){
function viewport() {
var e = window, a = 'inner';
if (!('innerWidth' in window )) {
a = 'client';
e = document.documentElement || document.body;
}
return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
}
});
// Get the correct window sizes with these declarations
windowHeight = viewport().height;
windowWidth = viewport().width;
});
What it Does:
When your page is 'ready' or is resized, the function calculates the correct window height and width (including scrollbar).
I assume you want to know the viewport width with scrollbar included, because the screen it self does not have a scrollbar. In fact the Screen width and heigth will be the computer screen resolution itself, so I'm not sure what you mean with screen width with the scroll bar.
The viewport however, the area where only the page (and scroll bars) is presented to the user, meaning, no browser menus, no bookmarks or whatever, only the page rendered, is where such scroll bar may be present.
Assuming you want that, you can measure the client browser viewport size while taking into account the size of the scroll bars this way.
First don't forget to set you body tag to be 100% width and height just to make sure the measurement is accurate.
body {
width: 100%;
// if you wish to also measure the height don't forget to also set it to 100% just like this one.
}
Afterwards you can measure the width at will.
Sample
// First you forcibly request the scroll bars to be shown regardless if you they will be needed or not.
$('body').css('overflow', 'scroll');
// Viewport width with scroll bar.
var widthWithScrollBars = $(window).width();
// Now if you wish to know how many pixels the scroll bar actually has
// Set the overflow css property to forcibly hide the scroll bar.
$('body').css('overflow', 'hidden');
// Viewport width without scroll bar.
var widthNoScrollBars = $(window).width();
// Scroll bar size for this particular client browser
var scrollbarWidth = widthWithScrollBars - widthNoScrollBars;
// Set the overflow css property back to whatever value it had before running this code. (default is auto)
$('body').css('overflow', 'auto');
Hope it helps.
As long as body is 100%, document.body.scrollWidth will work.
Demo: http://jsfiddle.net/ThinkingStiff/5j3bY/
HTML:
<div id="widths"></div>
CSS:
body, html
{
margin: 0;
padding: 0;
width: 100%;
}
div
{
height: 1500px;
}
Script:
var widths = 'viewport width (body.scrollWidth): '
+ document.body.scrollWidth + '<br />'
+ 'window.innerWidth: ' + window.innerWidth + '<br />';
document.getElementById( 'widths' ).innerHTML = widths;
I put a tall div in the demo to force a scroll bar.
Currently the new vw and vh css3 properties will show full size including scrollbar.
body {
width:100vw;
height:100vh;
}
There is some discussion online if this is a bug or not.
there is nothing after scrollbar so "rest of the window" is what?
But yes one way to do it is make another wrapper div in body where everything goes and body has overflow:none; height:100%; width:100%; on it, wrapper div also also has 100% width and height. and overflow to scroll. SO NOW...the width of wrapper would be the width of viewport
See Example: http://jsfiddle.net/techsin/8fvne9fz/
html,body {
height: 100%;
overflow: hidden;
}
.wrapper {
width: 100%;
height: 100%;
overflow: auto;
}
With jQuery you can calculate the browser's scrollbar width by getting the width difference when overflow: hidden is set and overflow: scroll is set.
The difference in width will be the size of the scrollbar.
Here is a simple example that shows how you could do this.
You can get the window width with scrollbar , that way:
function scrollbar_width() {
if (jQuery('body').height() > jQuery(window).height()) {
/* Modified from: http://jdsharp.us/jQuery/minute/calculate-scrollbar-width.php */
var calculation_content = jQuery('<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"><div style="height:100px;"></div>');
jQuery('body').append(calculation_content);
var width_one = jQuery('div', calculation_content).innerWidth();
calculation_content.css('overflow-y', 'scroll');
var width_two = jQuery('div', calculation_content).innerWidth();
jQuery(calculation_content).remove();
return (width_one - width_two);
}
return 0;
}
Check out vw: http://dev.w3.org/csswg/css-values/#viewport-relative-lengths
body {
width: 100vw;
}
http://caniuse.com/#search=vw
This is my solution for removing the 'scrollbar shadow', because scrollWidth didn't work for me:
canvas.width = element.offsetWidth;
canvas.height = element.offsetHeight;
canvas.width = element.offsetWidth;
canvas.height = element.offsetHeight;
It's easy, but it works. Make sure to add a comment explaining why you assign the same value twice :)

Categories