I want to know how many pixels from the top a user has scrolled down my page. So , the number of pixels ABOVE that can't be seen PLUS the number of pixels viewable in the current viewport.
With Jquery I'm using $(window).scrollTop() which is showing 612 pixels once scrolled to bottom of page, but $(document).height() reports a total height of 1276 pixels.
When I reach the bottom of the page the number I'm wanting to know will be 1276.
Hope that makes sense.
It sounds like what you're trying to get is the bottom of the window's current Y offset.
This can be calculated by summing the window's scrollTop() and innerHeight:
$(window).scrollTop() + window.innerHeight
$(window).scroll(function() {
$("#scrollTop").text($(window).scrollTop() + window.innerHeight);
$("#docHeight").text($(document).height());
}).scroll();
body {height: 2500px;}
div {position: fixed; top: 0; left: 0;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<span>scrollTop:</span> <span id="scrollTop"></span>
<br>
<span>document Height:</span> <span id="docHeight"></span>
</div>
To calculate how much the user has scrolled the page vertically in terms of pixels from the very top, in JavaScript, we would probe either window.pageYOffset, or in older versions of IE, one of several variants of document.body.scrollTop, whichever property is supported:
var scrollTop = window.pageYOffset || (document.documentElement || document.body.parentNode || document.body).scrollTop
Using jQuery instead, the equivalent would be:
var scrollTop = $(window).scrollTop()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
<div style="height:1000px"></div>
<p id="output" style="position:fixed; left:0; top:0; padding:10px; font-weight:bold">
You have scrolled the page by:
</p>
<script>
var output = document.getElementById('output')
window.addEventListener("scroll", function(){
var scrollTop = window.pageYOffset || (document.documentElement || document.body.parentNode || document.body).scrollTop;
output.innerHTML = 'You have scrolled the page by: ' + scrollTop +'px'
}, false)
</script>
<script>
/* ### jQuery version below. Uncomment to see: ### */
/*
var $output = $('#output')
$(window).on('scroll', function(){
var scrollTop = $(window).scrollTop()
$output.html( 'You have scrolled the page by: ' + scrollTop +'px' )
})
*/
</script>
</body>
Related
I use this code to check whether user has scrolled to the bottom code or not but it don't work on Google Chrome but it successfully works on Microsoft Edge.
In Google Chrome when i scroll to bottom and again scroll to top then it works but I don't know why.
Here is the code i am using.
<script>
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
alert("bottom!");
}
});
</script>
<!decotype html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div style="height: 4000px">Scroll down!</div>
</body>
</html>
Assuming you use a div to load some data... (Because of #load_data)
You need to get 3 values on scroll:
The scrolled position
The div height
The div scrollable height
This last one is an element property of the real element height, including its overflow.
Additionnally, you need to define what's near the bottom... In pixels.
So... In the below example, I'm faking an Ajax request. Just look for the code you need.
$(document).ready(function() {
// Function to replace Ajax in this demo.
function createContent(n){
var fakeContent = "";
for(i=0;i<n;i++){
fakeContent += i+"<br>";
}
$("#load_data").append(fakeContent);
}
// Simulate initial content...
createContent(100);
// The code you need
var near = 20; // pixels buffer yet to be scrolled when the Ajax triggers.
$("#load_data").on("scroll",function(){
if( $(this).scrollTop() + $(this).height() + near > this.scrollHeight ){
console.log("Faking Ajax...");
createContent(50);
}
});
}); // END ready
#load_data{
height: 150px;
width: 300px;
border: 1px solid grey;
overflow-y:scroll;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
There is 100 (0-99) lines on load.<br>
<div id="load_data"></div>
The problem is when you use margin (top or bottom) you should use .outerHeight(true) instead of .height or the sum of height and margin in this case. If you have padding is the same issue.
$(window).scroll(function(){
if($(window).scrollTop()+$(window).height()>$("h3").outerHeight( true ) ){
alert("bottom!")
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<h3 style="margin-top:2000px">hello world</h3>
</body>
<html>
About .outerHeight()
Get the current computed outer height (including padding, border, and
optionally margin) for the first element in the set of matched
elements or set the outer height of every matched element
.
This code makes this scroll indicator.
Can you please help me figure out how do the variable scrolled is calculated here?
Please explain why clientHeight is subtracted from scrollHeight and winScroll variable is divided by height then multiplied by 100?
// When the user scrolls the page, execute myFunction
window.onscroll = function() {
myFunction()
};
function myFunction() {
var winScroll = document.body.scrollTop || document.documentElement.scrollTop;
var height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
var scrolled = (winScroll / height) * 100;
document.getElementById("myBar").style.width = scrolled + "%";
}
<div class="header">
<h2>Scroll Indicator</h2>
<div class="progress-container">
<div class="progress-bar" id="myBar"></div>
</div>
</div>
<div class="content">
<h3>Scroll Down to See The Effect</h3>
<p>100 text line</p>
</div>
The clientHeight returns the height of the enclosing div. clientHeight reference
The scrollHeight read-only property is a measurement of the height of an element's content, including content not visible on the screen due to overflow. scrollHeight reference
An element's scrollTop value is a measurement of the distance from the element's top to its topmost visible content. scrollTop reference
Subtracting the clientHeight form scrollHeight provides the maximum scrollTop value that can be obtained. When the scroll reaches the bottom of the page, the scrollTop value becomes equal to that of the height.
The division with height and multiplication with 100 is to obtain the percent of scroll.
I want to implement a technique called scrollable div in GWT. What I am trying to do is the following.
If a user is on my page he can only see the viewport (green box in the image). All DOM elements that are in this viewport are visible to the user on page load. Alle DOM elements that are not on the viewport have not been loaded after a page has been loaded on page load (blue boxes in the image).
If the user drag and move the viewport, all dom elements become visible which come onto the viewport. If they are on the viewport they will be loaded via ajax.
The user can zoom in and out the viewport to make it bigger and smaller. Also, if elements that are invisible to the user and thus not loaded yet become visible, than they have to be loaded via ajax and displayed on the viewport.
How do I have to implement this with GWT?
If the user loads the page it looks like the following image:
The user can drag and move the viewport to 8 directions. These are top, top right, right, right bottom, bottom, bottom left, left and top left. The following image shows a movement to the left.
When the viewport moves new content should be loaded with ajax.
The viewport can also be zoomed in. In this case also new content should be loaded.
The viewport can also be zoomed out. Note that the viewport must be of fixed dimensions. Only the content should be zoomable.
UPD:
jsfiddle EXAMPLE: http://jsfiddle.net/hv57s/9/
UPD:
jsfiddle with zoom in/out buttons an functionality: http://jsfiddle.net/hv57s/11/
Answer based on this example: Indira.js Inifinite Scroll
<div id="scrollableDiv" data-scroll-callback="$('#load_button').trigger('click')">
<table>
...
<tbody id="scrollable_tbody">
<tr>
...
</tr>
</tbody>
<button id="load_button" onclick="load_more(page_number)">Show more</button>
</div>
<script>
var scroll_el_id = 'scrollableDiv';
var element = $('#scrollableDiv');
$(window).unbind('scroll.' + scroll_el_id).bind('scroll.' + scroll_el_id, function(event){
var scrollBottom = $(window).scrollTop() + $(window).height();
var elementBottom = element[0].scrollHeight + element.offset().top;
if(scrollBottom >= elementBottom){
eval($(element).attr('data-scroll-callback'));
$(window).unbind('scroll.' + scroll_el_id);
}
});
</script>
Next you just append to #scrollable_tbody AJAX-response, like:
function load_more(page){
$.ajax({type: "GET", url: 'some/url/load_more.php?page='+page,})
.done(function( html ) {
$('#scrollable_tbody').append(html);
});
}
UPD:
I think you should set big size for html,body like:
html, body{
min-width: 8192px;
width: 8192px;
min-height: 8192px;
height: 8192px;
}
And set viewport in size you want.
But maybe it will more easier if you will set some wrap div right after body tag with
div.wrap{
overflow: scroll;
-webkit-overflow-scrolling: touch;
/*Do not forget to change your_viewport_* to actual size, also you can do this via jQuery on the fly*/
max-height: your_viewport_height;
min-height:your_viewport_height;
height:your_viewport_height;
max-width: your_viewport_width;
min-height:your_viewport_width;
height:your_viewport_width;
}
and inside of this element Bigger div which will be scrollable.
div.huge{
min-width: 8192px;
width: 8192px;
min-height: 8192px;
height: 8192px;
}
HTML:
<html>
<head>
...
</head>
<body>
<div class="wrap">
<div class="huge">
...
</div>
</div>
</body>
</html>
Also do not forget to set scrolling control for all sides of elements, in example I have only Bottom line control, something like:
var scrollBottom = $(window).scrollTop() + $(window).height();
var elementBottom = element[0].scrollHeight + element.offset().top;
var scrollTop = $(window).scrollTop();
var elementTop = element.offset().top;
var scrollRight = $(window).scrollLeft() + $(window).width();
var elementRight = element[0].scrollWidth - element.offset().left;
var scrollLeft = $(window).scrollLeft();
var elementLeft = element.offset().left;
if(scrollBottom >= elementBottom && scrollTop <= elementTop && scrollRight >= elementRight && scrollLeft <= elementLeft){
eval($(element).attr('data-scroll-callback'));
$(window).unbind('scroll.' + scroll_el_id);
}
I didn't test this, and anyways you will have to play around with this. Hope I'm point you into right direction.
I need to change top-margin of an fixed div element from margin-top: 200px to margin top 0px after reaching the bottom of the page (or 200px from bottom) using vertical scrollbar.
And toggle return back if scrolling back to the top.
I guess some javascript/jQuery code code do that.
my html/layout code:
<div id="header" style="position: fixed; margin-top: 0px;">
Header content
</div>
<div id="main">
<div id="left" style="position: fixed; margin-top: 200px;">Google Ads here</div>
<div id="right">Content posts here</div>
</div>
<div id="footer">
Footer content
</div>
EDIT: Here are some images to make my question more clear.
normal state when you load the page:
problem when you scroll down, and the google ads column is in conflict with footer:
how it needs to be solved:
Derfder...
Voila, my proposed solution:
http://jsfiddle.net/YL7Jc/2/
The animation's a tad jerky, but I think it does what you want
(It's my take on an earlier s/o post:
Can I keep a DIV always on the screen, but not always in a fixed position? )
Let me know what you think!
Try below code which binds an event to window.scroll to check if the page hits the bottom (bottom in 200px) and moves the #left to top (margin-top: 0)..
DEMO: http://jsfiddle.net/6Q6XY/4/ ( added some demo code to see when it hits the bottom.)
$(function() {
var $left = $('#left');
$(window).bind('scroll', function() {
if (($(document).height()
- (window.pageYOffset + window.innerHeight)) < 200) {
$left.css('marginTop', 0);
} else {
$left.css('marginTop', 200);
}
});
});
Reference: https://stackoverflow.com/a/6148937/297641
You need to implement the window scroll function, this is a jquery implementation so please ensure you include the latest jquery libaries
$(window).scroll(function () {
if ($(window).scrollTop() + $(window).height() == $(document).height()) {
//if it hits bottom
$('#left').css("margin-top", "0px");
}
else {
$('#left').css("margin-top", "200px");
}
});
HTML
<div id="main" style="width: 960px; margin: 0px auto;">
<div id="left" style="position: fixed; top: 200px; left: 0px; background: #000; width: 100%; color: #fff;">Google Ads here</div>
<div id="right"></div>
</div>
JAVASCRIPT
<script type="text/javascript">
$(function() {
var documentHeight = $(document).height();
var windowHeight = $(window).height();
var left = $('#left');
var leftTopPosition = $('#left').css('top');
leftTopPosition = parseInt(leftTopPosition.substring(0, leftTopPosition.length-2));
$(window).scroll(function(){
var pageOffsetY = window.pageYOffset;
if((documentHeight - pageOffsetY - windowHeight) <= 200 && leftTopPosition == 200) {
left.stop().animate({
'top': '0px'
});
leftTopPosition = 0;
}
else if((documentHeight - pageOffsetY - windowHeight) > 200 && leftTopPosition == 0) {
left.stop().animate({
'top': '200px'
});
leftTopPosition = 200;
}
});
});
</script>
Hi Firstly you should have been more clearer in the first place before marking people down, as everyone give similar answers then it shows the question was not clear.
See Js Fiddle for a potential fix, please tweak as you need it with the pixels etc
for this problem you should use z-index in css
Try somethins like this
if ($(window).scrollTop() == $(document).height() - $(window).height())
{
document.getElementById(yourid).setAttribute("style","margin-top:0px");
}
Try this:
$(window).bind('scroll', function(){
if(($(window).height()-$(window).scrollTop())<200)
{
$('#left').css('margin-top',$(window).scrollTop());
}
else
{
$('#left').css('margin-top',200);
}
});
I have wrote a script to detect when I reach the div element which is a navigation bar and then I change it's css to position fixed and top 0 so it will be fixed to the top, the problem that it doesn't do that, it acts like scroll to top and it jumps to the beginning of the screen. (it's flickers)
Javascript
var currentScrollTop = 0;
var barMenuOriginalTopPos = $('#navigation').offset().top;
console.log('original:' + barMenuOriginalTopPos);
$(window).scroll(function() {
currentScrollTop = $(window).scrollTop();
console.log(currentScrollTop);
if(currentScrollTop >= barMenuOriginalTopPos && $('#navigation').hasClass('fixElementToTop') == false){
$('#navigation').addClass('fixElementToTop');
}
else if(currentScrollTop < barMenuOriginalTopPos && $('#navigation').hasClass('fixElementToTop') ){
$('#navigation').removeClass('fixElementToTop');
}
});
CSS
.fixElementToTop { position: fixed; top:0; z-index:100;}
Why
Here an non flickering solution via a jQuery plugin:
$(document).ready(function() {
$('#fixedElement').scrollToFixed({ marginTop: 0 });
});
Live example: http://bigspotteddog.github.com/ScrollToFixed/
Plugin's website: https://github.com/bigspotteddog/ScrollToFixed/
a css fixed bar on top of the screen
<div style="position:fixed;top:10px;left:10px">Nav bar</div>
Review:
sorry i didn't understand your initial question, here it goes, to avoid it flicking you should start the object with a fixed position, lets say:
<div style="height:120px">XXX</div>
<div id="navigation" style="position: fixed; top:120; z-index:100;">Navigation</div>
<div class="win" style="border: 1px solid; height: 900px;"></div>
the code:
$(window).scroll(function() {
currentScrollTop = 120-$(window).scrollTop();
console.log(currentScrollTop);
if (currentScrollTop<0) currentScrollTop=0
$("#navigation")[0].style.top=currentScrollTop+"px";
});
Set this line
var barMenuOriginalTopPos = $('#navigation').offset().top;
as
var barMenuOriginalTopPos = $('#navigation').offset().top + 6;
Refer LIVE DEMO