Vertical centre a div on a page - javascript

I have a question. I want to align a div on the vertical centre off the browser viewport. I understand how to do this and have written some code myself. But there is one thing that does not work:
// fetch al info I need
var windowHeight = $(window).height();
var pageTop = $(window).scrollTop();
var modalHeight = "98";
// Get the centre of the window
var divTop = (windowHeight - modalHeight) / 2;
// Add the scrollTop so the div will align in the middle of my current browser viewport
var divTop = divTop + pageTop;
var divTop = divTop + "px";
$('#modal_placeholder').css('top',divTop);
Now, the problem is that it will not get the correct scrollTop value ... it always says it's 0, like you are currently at the top of the page.
Can you help me out??

If you want to do this is js-way, you can do such like that:
var d = $(your_div),
div_height = d.height();
d.css({
position: 'absolute',
top: '50%',
margin: '-' + (div_height / 2) + 'px 0 0 0'
})

You could use a TABLE element: http://vidasp.net/CSS_Centering-horizontally-and-vertically.html

$(window).scrollTop() returns how far down the page you have scrolled. Try typing this into your address bar as you're in different positions on the page (any page.)
javascript:alert($(window).scrollTop());
Edit: It seems you already know this. The problem is that the variable is not being updated. When the page loads, $(window).scrollTop() has a value of 0. To update the value, try binding an event to updating that value.

Related

Get percent scrolled through an element jquery

I can't seem to figure out how to calculate this value
While scrolling down a page, I would like to make a function that return the percertage of 'scrolled through'.
So my 0 would be when the element is on the cusp of being shown (it's at the bottom of the window, 0 pixels shown) and 100 being when the element is completely passed (the element is over the top of the window, 0 pixels shown).
I would need that to do parralax with custom animations, to make an animation that starts when the element is shown, and animates through until the element is gone.
EDIT: All Paralax plugins I see seem to force you in premade animations. I'd like to animate my own thing, so thats why I need that percent value.
After asking the question, I didn't just sit on my hands and continued working on this. This seems to do what I wish to do.
function ScrollPercent(jQEl){
var currY = $('html').scrollTop();
var elH = $(jQEl).height();
var elTop = $(jQEl).offset();
elTop = elTop.top;
var fullH = $('html').height();
var zero = elTop-elH;
var hundred = elTop+$( window ).height();
var scrollPercent = (currY-zero)/(hundred-zero);
return scrollPercent;
}
I've never used jquery. But I can help you with this function.
function ScrollPercent(selector) {
var currY = document.documentElement.scrollTop;
var elH = document.querySelector(selector).offsetHeight;
var elTop = document.querySelector(selector).offsetTop;
var fullH = document.documentElement.scrollHeight;
var zero = elTop - elH;
var hundred = elTop + window.innerHeight;
var scrollPercent = (currY - zero) / (hundred - zero);
return scrollPercent;
}

DIV fades onto another DIV

How would you make it if the user scrolls down a page, the top DIV fades into the DIV underneath it, and so on and so forth until it fades to a white background?
Here's a jsfiddle of my attempt: https://jsfiddle.net/fkgzzxku/
And here's it's hosted on a staging server for a better illustration: http://bound.staging.wpengine.com/
var target = $('div.slider-item');
var targetHeight = target.height();
var containerHeight = $('#intro-slider').outerHeight();
var maxScroll = containerHeight - targetHeight;
var scrollRange = (maxScroll / (target.length - 1)) + 250; // originally 450
$(document).scroll(function(e) {
var scrollY = $(window).scrollTop();
var scrollPercent = (scrollRange - scrollY % scrollRange) / scrollRange;
var divIndex = Math.floor(scrollY / scrollRange);
target.has(':lt(' + divIndex + ')').css('opacity', 0);
target.eq(divIndex).css('opacity', scrollPercent);
target.has(':gt(' + divIndex + ')').css('opacity', 1);
});
But the DIVs don't completely fade to 0, they fade to a number close to 0 so I feel like my math is wrong.
I also found that if the user scrolls too fast (by pressing page down, etc) you can see all 3 of the images faded into another.
Thanks!
I think because scrollY%scrollRange is never equal to scrollRange your scrollPercent is never 0. You can use scrollPercent= Math.round(scrollPercent*10)/10; after calculating scrollPercent to round it off to 0.
Moreover the problem caused by scrolling too fast seems to be caused by the has function replacing it with slice function works fine for me ( I can't understand why ). Here is the updated code
$(document).scroll(function(e) {
var scrollY = $(window).scrollTop();
var scrollPercent =(scrollRange - scrollY % scrollRange) / scrollRange;
var divIndex = Math.floor(scrollY / scrollRange);
target.slice(0,divIndex).css('opacity', 0);
target.eq(divIndex).css('opacity', scrollPercent);
target.slice(divIndex+1).css('opacity', 1);
});
This works without rounding off scrollPercent. Hope it helps

Detect percent on screen of an element

I'm trying to detect what % of the element can be seen on the current window.
For example, if the user can only see half the element, return 50. If the user can see the whole element, return 100.
Here's my code so far:
function getPercentOnScreen() {
var $window = $(window),
viewport_top = $window.scrollTop(),
viewport_height = $window.height(),
viewport_bottom = viewport_top + viewport_height,
$elem = $(this),
top = $elem.offset().top,
height = $elem.height(),
bottom = top + height;
return (bottom - viewport_top) / height * 100;
}
But it doesn't seem to be working. Can anyone help me out in achieveing this I seem to be spinning gears.
What you want to get is the amount of pixels that the element extends past the top and bottom of the viewport. Then you can just subtract it from the total height and divide by that height to get the percentage onscreen.
var px_below = Math.max(bottom - viewport_bottom, 0);
var px_above = Math.max(viewport_top - top, 0);
var percent = (height - px_below - px_above) / height;
return percent;
One thing to note is that jQuery's height method won't include padding. You probably want to use .outerHeight for that.
Your $elem = $(this)assignment seems wrong, here function scoping means this refers to the function you're in (ala ~ the function getPercentOnScreen), try referencing by $elem = $('#yourElementId')instead.
if you only want to calculate percent of element then just do this
function getPercentOnScreen(elem) {
$docHeight = $(document).height();
$elemHeight = $(elem).height();
return ($elemHeight/$docHeight)* 100;
}

IE8 JavaScript issue

I need to have a bottom bg at the bottom of the page all the time, so I came up with a decision to get window height and main content height and calculate if the bottom part should be pushed down or not. The problem came up when the content block was too short and the computer screen was much bigger, so the bottom bg was right at the end of the the content and had nothing after till the end of the bottom screen. Hopefully it makes sense ) I decided to add some height inside of the content to make it longer so it fills up the bottom space and very bottom gap disappear.
Here is the JavaScript I used to fix it:
window.onload=function(){
var winHeight = window.innerHeight;
var fixIt = winHeight - 200;
var divHeight = document.getElementById('bottomDiv').clientHeight;
alert(winHeight - divHeight);
if (divHeight < winHeight) {
var fire = document.getElementById('innerDiv').style.height = fixIt + "px";
}
};
Problem: this script works fine and does its job well in all browsers but not IE7-IE8. Can you please help to get a solution for old IE browsers?
Thanks,
Art
window.onload=function(){
// v---------------------------------------v
var winHeight = window.innerHeight || document.documentElement.clientHeight;
var fixIt = winHeight - 200;
var divHeight = document.getElementById('bottomDiv').clientHeight;
alert(winHeight - divHeight);
if (divHeight < winHeight) {
var fire = document.getElementById('innerDiv').style.height = fixIt + "px";
}
};
Maybe instead you could apply your "bottom" background to the html element, then cover it up with a different background (possibly in your div#content) in the upper region.
Otherwise, it seems innerHeight isn't supported in IE8.
window.innerHeight ie8 alternative
Try
var winHeight = document.documentElement.clientHeight

offsetHeight and offsetWidth calculating incorrectly on first onclick event, not second

I have written the following script to display a hidden element, then fix it's position to the center of the page.
function popUp(id,type) {
var popUpBox = document.getElementById(id);
popUpBox.style.position = "fixed";
popUpBox.style.display = "block";
popUpBox.style.zIndex = "6";
popUpBox.style.top = "50%";
popUpBox.style.left = "50%";
var height = popUpBox.offsetHeight;
var width = popUpBox.offsetWidth;
var marginTop = (height / 2) * -1;
var marginLeft = (width / 2) * -1;
popUpBox.style.marginTop = marginTop + "px";
popUpBox.style.marginLeft = marginLeft + "px";
}
When this function is called by an onclick event, the offsetHeight and offsetWidth are calculated incorrectly, thus not centering the element correctly. If I click the onclick element a second time, the offsetHeight and offsetWidth calculate correctly.
I have tried changing the order in every way I can imagine, and this is driving me crazy! Any help is very much appreciated!
I am guessing your height and width are not defined on the parent. See this fiddle where it works fine. Boy I'm smart. http://jsfiddle.net/mrtsherman/SdTEf/1/
Old Answer
I think this can be done a lot more simply. You are setting the top and left properties to 50%. This will place the fixed element slight off from the center. I think you are then trying to pull it back into the correct position using negative margins. Instead - just calculate the correct top/left values from the start and don't worry about margin. Here is a jQuery solution, but it can be easily adapted to plain js. I also think your current code won't work if the window has been scrolled at all.
//this code will center the following element on the screen
$('#elementid').click(function() {
$(this).css('position','fixed');
$(this).css('top', (($(window).height() - $(this).outerHeight()) / 2) + $(window).scrollTop() + 'px');
$(this).css('left', (($(window).width() - $(this).outerWidth()) / 2) + $(window).scrollLeft() + 'px');
});

Categories