Trying to trigger event on certain scroll height using javascript - javascript

var amount = document.getElementsByClassName("cart-total-qty")[0].innerHTML;
console.log(amount);
var body = document.body,
html = document.documentElement;
var height = Math.max( body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight );
var tenPercent = height*.9
window.addEventListener("scroll", function() {
scrollAmount = window.scrollY;
if(scrollAmount == tenPercent){
alert("It's happening (Insert Ron Paul)");
}
});
In my code above i am getting the height of the page using an example i found here: How to get height of entire document with JavaScript?
I am then trying to trigger an event once the user has scrolled to the bottom ten percent of the page. The problem is that scrollAmount does not ever reach within 10% of height
In my example height is returned as 1280 and scrollAmount never returns higher then 1040 while scrolling, but the strange part is that if i change the height of my browser i get different results for scrollAmount when i scroll to the bottom.

First of all, it is expected that scrollAmount would return a value significantly lower than content height of the document. If you look closer, maximum value of it is actually (content height - window height). Think of it like this: suppose your content was just one pixel longer than available window height, in that case what should be the maximum scrollAmount? I'd expect it to be 1.
So replace your tenPercent = height*.9 with tenPercent = (height-window.innerHeight)*.9
Second, you scroll in steps of 100px or so. Sure some animation may be there, but event doesn't fire constantly for every possible value of scrollAmount. It is unlikely that during scroll, scrollAmount would exactly be equal to tenPercent. So replace your scrollAmount == tenPercent with scrollAmount > tenPercent

Related

Autoscroll if initial document is smaller than the size of the window

I am using jQuery and javascript to dynamically load data from my server when the user scrolls to the bottom of the page:
$(window).scroll(function(){
var scrollTop = $(document).scrollTop();
var windowHeight = $(window).height();
var bodyHeight = $(document).height() - windowHeight;
var scrollPercentage = (scrollTop / bodyHeight);
if(scrollPercentage == 1) {
// Load content
}
}
});
The only problem is that if the height of the viewport is large enough, then the initial document height would be smaller than the height of the viewport. Then, the user would not be able to scroll and my code would not work. What is the best way to deal with this? I thought about repeatedly checking in the javascript if the heigh of the document exceeds the height of the viewport, and continuing to load in content until it does exceed the height of the viewport:
while ($(document).height() == $(window).height()) {
if (working == false) {
working = true;
getData();
}
}
This working variable is a variable I set to true whenever I fetch data. Then, within the ajax callback I have a timeout that change working to false in 1 second. the getData function fetches the data from my server. However, the page seems to just get stuck on this while loop. (It doesn't load)

Moving a div relative to what vertical position you are on a scrollable page

Imagine I have a website that overflows three times the viewport height. I can scroll on this website from top to bottom.
Is it possible to create a div that moves from the top of the viewport to the bottom relative to the amount of the total page that has been scrolled?
Example - Would someone mind helping me achieve something like this? Not sure how it was done.
Edit:
var scrollValue;
var percent;
var body = document.body,
html = document.documentElement;
var height = Math.max( body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight );
$(document).ready(function(){
$("button").click(function(){
scrollValue = $("body").scrollTop();
percent = (scrollValue / height) * 100;
alert(percent);
});
});
You may try using jQuery scrollTop(). See the demo at jquery.com.
Idea:
If you understand the both type of use of this function (with/without args) you can use this same function to get the current scroll position of your custom scrollbar, then trigger your div to be scrolled to the relative scrolling position.
Alternate Task: If you want to scroll the custom scrollbar on mousewheel move, I recommend to use jquery mousewheel plugin-
$(window).mousewheel(function(turn, delta) {
if (delta == 1) // going down
else //going up
// all kinds of code
return false;
});

JavaScript/jQuery inquiries

JavaScript/jQuery:
$(document).ready(function(){
"use strict";
var windowHeight = $(window).height();
var homePageHeight = $('#main').height();
if (windowHeight >= homePageHeight){
$('#main').css("padding-top", (((windowHeight-homePageHeight)/2))-130);
$('#main').css("padding-bottom", (((windowHeight-homePageHeight)/2))-130);
}
$(window).resize(function() {
var windowHeight = $(window).height();
var homePageHeight = $('#main').height();
if (windowHeight >= homePageHeight){
$('#main').css("padding-top", ((windowHeight-homePageHeight)/2));
$('#main').css("padding-bottom", ((windowHeight-homePageHeight)/2));
}
});
Basically I have a section here on my HTML that handled by that code above:
<section id="main">
</section>
I understand that these codes handles the size of the screen on the top but can anyone help me understand in layman's term how does the windowHeight and homePageHeight works? You simply explain it to me each function on the top line by line if that's possible.
$(window).height(); assigned to windowHeight is height of the (browser) window or viewport. With respect to the web browsers the viewport here is visible portion.
$('#main').height(); assigned to homePageHeight is height of the div or section identified by ID main
(windowHeight >= homePageHeight) checks whether browser height is greater than height of section #main
if windowHeight greater than or equal to homePageHeight, then a padding is added to top and bottom of #main
$('#main').css("padding-top", (((windowHeight-homePageHeight)/2))-130);
$('#main').css("padding-bottom", (((windowHeight-homePageHeight)/2))-130);`
Look at the JQuery Docs. The function height() is your favourite.
The measured height = (Height of Element) - (margin + border-width + padding of Element)
windowHeight is a variable, it's value is being set to the height of the browser window.
homePageHeight is also a variable, it's value is being set to the height of div#main.
When the document loads, it's checking if windowHeight is greater than or equal to homePageHeight; if it returns true, it is applying some css using jQuery.
When the window resizes, it's doing a similar thing again.
The rest of the code is very self-explanatory. If you still do not understand it, you need to read up on Javascript and jQuery.

prevent overflow of absolutely positioned dynamic div

I need to get the height and width of a dynamically generated div inside a loop.
Details
I'm dynamically setting the left and top values of a positioned absolute div. This div is in a loop, thus its width, height and position change at an interval n.
(It's basically a div that appears at random places on a page every n seconds.)
The challenge I'm facing is that this div needs to be inside the parent at all times, <body> tag in this case. I have it set to position:relative and even overflow:hidden though it won't help.
Here's a fiddle to make things easier.
Fiddle 1 outside the loop , Fiddle 0 insdie the loop
You will see that because the x and y values are randomly generated the div overflows.
I have found that in order to keep the div in the body it's height and width must be retrieved and calculated with the parent to get the difference in size.
So I can use it the css like
var heightdiff = parentHeight - divHeight;
var widthdiff = parentWidth - divWidth;
in the css via jQuery
top: Math.floor((Math.random()*heightdiff)+0;
left: Math.floor((Math.random()*widthdiff)+0;
Perhaps I'm making a simple mistake but I've tried everything I can think of. To recap all I need to do is to get the height and width of div.
I modified your script :
http://jsfiddle.net/yMT56/1/
Why using document as base ?
var docw = $(document).width();
var doch = $(document).height();
Use body
var docw = $('body').width();
var doch = $('body').height();
Or better, div's parent (requires you to append your div to a container before) :
var docw = $newdiv.parent().width();
var doch = $newdiv.parent().height();
The problem here is that the div has no content and so on no width and height at the moment you calculate it. So I created it at the beginning (notice i added <body> tag in the html part : i don't know how fiddlejs handles this case) :
$newdiv = $('<div/>').css({
'position':'absolute',
'display':'block'
}).html("Hi there, this should appear with in the body.<br/> Just wait it will overflow").appendTo( 'body' );
//parent size, in this case body
var docw = $('body').width();
var doch = $('body').height();
//calculating div size, before it's set, wrong!!
var divh = $newdiv.height();
var divw = $newdiv.width();
I also added a Math.max control to be sure results won't be negatives, especially in case div is larger than his parent.
//positions for x and y
var posx = Math.max((Math.random() * (wdiff) +1).toFixed(), 0);
var posy = Math.max((Math.random() * (hdiff) +1).toFixed(), 0);
And, at the end, only put position for the div :
$newdiv.css({
'left':posx+'px',
'top':posy+'px'
}).fadeIn(2000).fadeOut(2000, function(){
Maybe with that solution, a first div will be displayed before loop starts. A solution would be to use visibility:hidden property, to hide div but always be able to got his width and height.

Get scrollable height of a page

First of all,I would like to know the difference between these terms:
- $(window).height()
- $(document).height()
- $(window).scrollTop()
These terms look somewhat similar to me and I am unable to understand the clear difference between them. Here are my answers:
$(window).height() : Gives the height of window which a user can see.
$(document).height() : Gives total height of document. This can be more/less than window height depending upon the content on the page.
$(document).scrollTop() : gives the vertical position of scrollbar in window.
Real Question:
I am trying to implement lazy loading kinda thing where I need to make a call to server when scrollbar has crossed a point 200px from bottom of page. I am unable to use the above values to get this.
Any help would be appreciated.
The window is the area that you can see - as if your screen is a window and you are looking through at the document. The document is the entire document - it could be shorter or much longer than the window.
This is the math you need:
if( $(document).height() - $(document).scrollTop() < 200 ){
//Do something
}
$(window).height(); // returns height of browser viewport
$(document).height(); // returns height of HTML document
$(window).scrollTop(); //Get the current vertical position of the scroll bar for the first element in the set of matched elements or set the vertical position of the scroll bar for every matched element.
$(window).scrollHeight(); //Height of the scroll view of an element; it includes the element padding but not its margin.
Eventually, I figured out what should be the calculations after understanding these terms. Thanks to the answers. I was almost right in my definitions.
function (isScrollable) {
var isUserAtBottom = ($(window).height() + $(window).scrollTop() + 200 > $(document).height());
if (isUserAtBottom) {
// Do something (Like Ajax call to server to fetch new elements)
return true;
}
}

Categories