Scroll to Bottom in Jquery is not working properly - javascript

I make the scroller with top to bottom and bottom to top simultaneously. I did most of them. From bottom to top is working perfect and for top to bottom only causing somehow problem is works only if i increase the height of the div container. I am not sure where i could change the values to make it workable.
Here is the fiddle
JS
var percentageToScroll = 89;
var height = $(document).innerHeight();
var scrollAmount = height * percentageToScroll / 100;
alert(scrollAmount);
var overheight = jQuery(document).height() - jQuery(window).height();
//alert(overheight);
jQuery("html, body").animate({
scrollTop: scrollAmount
}, 900);
I did with percentage to animate the scroll.
You can click the bottom button in fiddle to see that. I want to scroll only 89% but it scroll fully to the bottom.
Much Appreciated your Help !!!

The top of the viewport will be at 89% of the document.
If for example your document is 100px in height, the top 89px will be off-screen and the bottom 11px are displayed (for as far as possible). If however you're screen-size is larger than this 11px, it can't scroll down that much.
What you probably want is:
var scrollAmount = ($(document).innerHeight() - $(window).height()) * percentageToScroll / 100;

Please try this it may helps you
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()){
alert("at bottom!");
}
});
You can also adjust it according to your requirment by reducing its height
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() > $(document).height()-100){
alert("near bottom!");
}
});

Related

Button sticks to bottom of page jQuery

So I did not find anything related to this, only making the button scrolls down to bottom of page on click but I already got this.
My problem is:
I got an 'Explore Button' on top a slide show that when you click on it the page scrolls down, the thing is, in some screens the slideshow is bigger than the size of the window so you can't see the button unless you scroll down (therefore no point in having the button). I fixed it by adding:
$(document).ready(function() {
var slideHeight = $('.item').height();
var headerHeight = $('header').height();
var windowHeight = $(window).height();
$('.exploreImage').css('bottom', (Math.max(headerHeight + slideHeight, windowHeight) - windowHeight) + 20 + "px");
});
But now when I scroll down I want the button to scroll down and stay at the bottom of the window (until a certain height which is the end of the slide show).
I've got so far something similar which is:
$(window).on('scroll', function() {
$('.exploreImage').css('bottom', 0 + "px");
});
But this puts the button at the bottom of the slide show when it scrolls and not bottom of the windows as I want to!
Notice: I need to get this done with jQuery.
Thanks for your help guys!
EDIT: fiddle: https://jsfiddle.net/1fr27eLu/7/ but the jQuery doesn't seem to work there!
When combined with the other answer, you could use a form of throttle along with the animate() method.
I haven't got it perfect, but hopefully you'll see the value.
$(window).scroll( $.throttle( 250, btnScroll ) );
jsFiddle Demo
Resources:
http://benalman.com/projects/jquery-throttle-debounce-plugin/
https://css-tricks.com/the-difference-between-throttling-and-debouncing/
http://www.paulirish.com/2009/throttled-smartresize-jquery-event-handler/ (see bottom comments)
This is a poor example, but it may give you something to start with. Incorrect positioning of button has something to do with this:
https://api.jquery.com/scrollTop/
The vertical scroll position is the same as the number of pixels that are hidden from view above the scrollable area. If the scroll bar is at the very top, or if the element is not scrollable, this number will be 0.
Anyway, here is the sample code that might put you onto the right track:
var screenWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0); //Max of page size vs window size, or zero
var screenHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
screenHeight = screenHeight - 100; //correct for jsFiddle
var st, btnFixed=false, bd = $('#btnDIV');
$(window).scroll(function(){
st = $(window).scrollTop();
$('#rpt').html( st +'/'+ screenHeight); //DEV
if (st < screenHeight && !btnFixed){
bd.css({'top':st*1.3});
}else{
bd.css({'top': screenHeight+'px'});
btnFixed = true
}
if (st < screenHeight && btnFixed){
bd.css({'top':st*1.3});
btnFixed = true
}
});
html,body{
100%;
}
div{
position:relative;
}
#wrap{
height:2000px;
}
#btnDIV{
position:fixed;
top:0;
left:0;
background:red;
overflow:hidden;
z-index:2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="btnDIV"><button class="exploreImage">Explore</button></div>
<div id="rpt"></div>
<div id="wrap"></div>
#rpt{position:fixed;top:0;right:0;height:40px;width:100px;background:wheat;}
jsFiddle Demo

followTo issue with higher resolutions

I use this snippet to make an element "stop" at a certain point when scrolling.
$.fn.followTo = function (pos) {
var $this = this,
$window = $(window);
$window.scroll(function (e) {
if ($window.scrollTop() > pos) {
$this.css({
position: 'absolute',
top: pos
});
} else {
$this.css({
position: 'fixed',
top: 0
});
}
});
};
$('#braille').followTo(865);
The problem is that if there's not enough space to scroll (in higher resolutions), it's not positioned correctly.
It's important that you watch these 2 videos to understand how it works.
1920x1080: https://www.youtube.com/watch?v=WjT8FKAKTxA
It's properly positioned.
2775x1514: https://www.youtube.com/watch?v=oqQXm8BsfYA
Here instead as you can see it's not in the right place because there's not enough space to scroll
Resolutions until about 1190px height are ok, with higher resolutions there's this problem.
How can I solve this..? Can I set a followTo starting from the bottom of the page? Or set it in percentage? Or say "if height is > than 1190 just put that there"....
Here is the live webpage. To see what I'm talking about just zoom out like 3 times the resolution of your browser and try to scroll the page. The braille image isn't positioned properly under the music staff and above the yellow paragraph.
The short answer is yes, you can set followTo relative to the bottom of the page using $(document).height() - pos. The basic principle is:
$(window).scrollTop() == $(document).height() - $(window).height()
To change the followTo to work relative to the bottom of the page:
if ($(document).height() - $window.height() - $window.scrollTop() < pos)
To use a percentage you could do the calculation:
var percentageDownPage = $window.scrollTop() / ($(document).height() - $(window).height()) * 100;
if (percentageDownPage > pos) { /* your code*/ }

Div to follow scrollbar proportionally on a page

I'm now struggling on a sticky element that should scroll proportionally on a page. From top to the footer despite the page's height. So it's actually stick to the top of the scrollbar in the beginning and then to the bottom at the end. Or it just follows the scroll wheel.
Is there any chance to do it with jQuery ?
Below is the starting code with usual "sticky" div.
$(window).scroll(function(){
$("#sticky")
.animate({"marginTop":($(window).scrollTop())+"px"}, "fast");});
https://jsfiddle.net/flakessp/cxr78xc8/
Do you mean something like this?
$(window).scroll(function() {
// calculate the percentage the user has scrolled down the page
var scrollPercent = 100 * $(window).scrollTop() / ($(document).height() - $(window).height());
// get the height of the sticky element
var stickyHeight = $('.sticky').height();
// calculate the margin top of the sticky element
var marginTop = (($(window).height() - stickyHeight) / 100) * scrollPercent;
// set margin top of sticky element
$('.sticky').css('marginTop', marginTop);
});
Fiddle
So, this one was a little tricky, but here it is:
JSFiddle example
Basically, we're using a couple things here:
Scroll direction detection with this section:
var lastScrollPos = 0,
...
lastScrollPos < $window.scrollTop()
Then, you forgot to factor in things like document and window height. scrollTop does exactly what it says and only gives you the number from the top of the viewport to the top of the document. So we add in the visible height as well with $(window).height().
Then it's just a matter of whether we factor in the height of the element too (hence the ternary operator adding 0 or $('#sticky').height() depending on our scroll direction detection from the earlier section.
Anyhow, here's the full JS:
var lastScrollPos = 0,
$window = $(window),
$document = $(document),
$sticky = $('#sticky');
$(window).scroll(function(){
$sticky
.animate({"top":((($window.scrollTop() + (lastScrollPos < $window.scrollTop() ? $window.height() - $sticky.height() : 0))/$document.height()) * 100)+"%"}, "fast");
});

get percentage scrolled of an element with jquery

I'm trying to get an div to animate 0% - 100% relative to the percentage scrolled of an element.
Now I've set up a few variables, but I'm having trouble trying to calculate the height of one by percentage.
We can set the starting width quite easily and detect the scroll easily enough too, as can we get the height of the element that'll trigger the animation, I just can't get it as a percentage.
If I can figure out how to return the percent of conheight scrolled then this should be easy.
$(window).scroll(function() {
// calculate the percentage the user has scrolled down the page
var scrollPercent = ($(window).scrollTop() / $(document).height()) * 100;
$('.bar-long').css('width', scrollPercent +"%" );
});
Here's a jsfiddle, http://jsfiddle.net/SnJXQ/
This is animating bar-long based on the percent scrolled of the body element.
Animates from 0% - 100% (well, it doesn't really, but I can't figure out why).
What I'd like to do is get scroll percent of the .post div, then animate bar-long relative to that.
ie. Scrolled 10% of .post, .bar-long is 10% width, scrolled 70% of .post, .bar-long is 70% width.
Demo
Your problem is the same as How to get horizontal scrolling percentage of an HTML element in JavaScript?, but vertically.
Then, to get the vertically scrolled percentage, use
/* JS */ var scrollPercentage = 100 * containeR.scrollTop / (containeR.scrollHeight-containeR.clientHeight);
/*jQuery*/ var scrollPercent = 100 * $(containeR).scrollTop() / ($(containeD).height() - $(containeR).height());
In your case, containeR = window; containeD = document:
var scrollPercent = 100 * $(window).scrollTop() / ($(document).height() - $(window).height());
Ok I see what you are trying to achieve....in fact I just did something very similar. Most solutions I found out there also were only for full page examples with window or document properties. Instead I needed this in a specific div which in my case was actually used to update the horizontal position of another div.
First, you are going to want the scroll event attached to your $('.post')
Next, the height of the $('.content') is going to equal your actual Scroll Height
Lastly, apply your percentage formula : (Y / (scrollHeight - postHeight)) * 100 = scrollPercent
So instead of using document or window attributes your code should be as follows:
$('.post').scroll(function() {
var currY = $(this).scrollTop();
var postHeight = $(this).height();
var scrollHeight = $('.content').height();
var scrollPercent = (currY / (scrollHeight - postHeight)) * 100;
});
You can find the fiddle here: JS Fiddle For Div Scroll Percentage
The current project where I have implemented this is located here: Vertical Scroll Drives Horizontal Position
I hope this solves your problem :)
Let's say you want to keep track of the scroll of some document found in some IFrame in your page.
object.addEventListener("scroll", documentEventListener, false);
Then your event listener should look like this:
function documentEventListener(){
var currentDocument = this;
var docsWindow = $(currentDocument.defaultView); // This is the window holding the document
var docsWindowHeight = docsWindow.height(); // The viewport of the wrapper window
var scrollTop = $(currentDocument).scrollTop(); // How much we scrolled already, in the viewport
var docHeight = $(currentDocument).height(); // This is the full document height.
var howMuchMoreWeCanScrollDown = docHeight - (docsWindowHeight + scrollTop);
var percentViewed = 100.0 * (1 - howMuchMoreWeCanScrollDown / docHeight);
console.log("More to scroll: "+howMuchMoreWeCanScrollDown+"pixels. Percent Viewed: "+percentViewed+"%");
}

jQuery fixed sidebar that moves with content if overflow

I have the following fiddle: http://jsfiddle.net/yFjtt/1/
The idea is that the user can scroll PAST the header to make the sidebar 'stick' in place while they scroll further down the page.
As they near the bottom of the page it should then work out how much space is left and how much space the sidebar needs and the add some negative margin to move the sidebar upwards whilst maintaining the fixed position.
Upto here it all works fine.
The next problem is making sure that the sidebar only moves up as far as it needs to and should remain about 10 pixels from the bottom. This way the sidebar will be fixed until it needs to move upward to reveal its content and then once it's all shown become stuck again about 10 pixels from the bottom.
Here is where I have tried to achieve this (see fiddle for full code):
if( $(window).scrollTop() > (documentHeight - sidebarHeight) ) {
if( offsetBottom < 10) {
}
else {
$('div.sidebar').stop(true,false);
$('div.sidebar').animate({'margin-top':offset}, 300);
}
} else {
$('div.sidebar').stop(true,true);
$('div.sidebar').css({'margin-top':'0'});
}
However the sidebar STILL moves too far up the page... Can anyone help? I'm sure it's just a simple mistake working out the offset from the bottom.
I think you had a good try, except I'm not sure what those animations are doing there. Basically you need 3 checks, first to see if the use is above the header, second to check if they're between the header and the bottom most limit for the sidebar, and lastly if they're below that point. Then simply swap and change classes and modify top value as necessary.
jsFiddle
var sidebarHeight = $('div.sidebar').height();
var documentHeight = $(document).height();
var headerHeight = $('div.header').height();
$(window).scroll(function() {
var margin = 10;
var sidebar_offset = documentHeight - sidebarHeight - (margin * 2); // double margin to account for top and bottom margins
if ($(window).scrollTop() > headerHeight && $(window).scrollTop() < sidebar_offset ) {
// below header, but above the sidebar offset limit
$('div.sidebar').addClass('fixed');
$('div.sidebar').css('top', '');
}
else if ( $(window).scrollTop() <= headerHeight ) {
// above header
$('div.sidebar').removeClass('fixed');
$('div.sidebar').css('top', '');
}
else {
// past the sidebar offset limit
$('div.sidebar').removeClass('fixed');
$('div.sidebar').css('top', documentHeight - sidebarHeight - margin);
}
});​

Categories

Resources