document.ontouchmove and scrolling on iOS 5 - javascript

iOS 5 has brought a number of nice things to JavaScript/Web Apps. One of them is improved scrolling. If you add
-webkit-overflow-scroll:touch;
to the style of a textarea element, scrolling will work nicely with one finger.
But there's a problem. To prevent the entire screen from scrolling, it is recommended that web apps add this line of code:
document.ontouchmove = function(e) {e.preventDefault()};
This, however, disables the new scrolling.
Does anyone have a nice way to allow the new scrolling within a textarea, but not allow the whole form to scroll?

Update Per Alvaro's comment, this solution may no longer work as of iOS 11.3.
You should be able to allow scrolling by selecting whether or not preventDefault is called. E.g.,
document.ontouchmove = function(e) {
var target = e.currentTarget;
while(target) {
if(checkIfElementShouldScroll(target))
return;
target = target.parentNode;
}
e.preventDefault();
};
Alternatively, this may work by preventing the event from reaching the document level.
elementYouWantToScroll.ontouchmove = function(e) {
e.stopPropagation();
};
Edit For anyone reading later, the alternate answer does work and is way easier.

The only issue with Brian Nickel's answer is that (as user1012566 mentioned) stopPropagation doesn't prevent bubbling when you hit your scrollable's boundaries. You can prevent this with the following:
elem.addEventListener('touchstart', function(event){
this.allowUp = (this.scrollTop > 0);
this.allowDown = (this.scrollTop < this.scrollHeight - this.clientHeight);
this.prevTop = null;
this.prevBot = null;
this.lastY = event.pageY;
});
elem.addEventListener('touchmove', function(event){
var up = (event.pageY > this.lastY),
down = !up;
this.lastY = event.pageY;
if ((up && this.allowUp) || (down && this.allowDown))
event.stopPropagation();
else
event.preventDefault();
});

For anyone trying to acheive this with PhoneGap, you can disable the elastic scrolling in the cordova.plist, set the value for UIWebViewBounce to NO. I hope that helps anyone spending ages on this (like i was).

ScrollFix seems to be perfect solution. I tested it and it works like a charm!
https://github.com/joelambert/ScrollFix
/**
* ScrollFix v0.1
* http://www.joelambert.co.uk
*
* Copyright 2011, Joe Lambert.
* Free to use under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*/
var ScrollFix = function(elem) {
// Variables to track inputs
var startY, startTopScroll;
elem = elem || document.querySelector(elem);
// If there is no element, then do nothing
if(!elem)
return;
// Handle the start of interactions
elem.addEventListener('touchstart', function(event){
startY = event.touches[0].pageY;
startTopScroll = elem.scrollTop;
if(startTopScroll <= 0)
elem.scrollTop = 1;
if(startTopScroll + elem.offsetHeight >= elem.scrollHeight)
elem.scrollTop = elem.scrollHeight - elem.offsetHeight - 1;
}, false);
};

It was frustrating to discover a known problem with stopPropagation and native div scrolling. It does not seem to prevent the onTouchMove from bubbling up, so that when scrolling beyond the bounds of the div (upwards at the top or downwards at the bottom), the entire page will bounce.
More discussion here and here.

Related

.clone().appendTo - Replace element styles not working?

I have individual three arrows. on click; I want the div below them (letsChat) to change styles and I want to clone and append relevant information in that div. I also want it to revert back to it's original state when it is clicked again or if orientation is changed to portrait.
document.querySelector('#compositionArrow').onclick = function(){
var letsChat = document.querySelector('.lets-chat');
var letsChatButton = document.querySelector('.lets-chat a');
var compositionArrow = document.querySelector('#compositionArrow')
var compositionText = document.querySelector('.composition-text');
if (letsChatButton.style.display='flex' && window.matchMedia("(orientation: landscape)").matches) {
compositionArrow.style.transform='rotate(180deg)';
//letsChat.appendChild(compositionText).cloneNode(true);
//compositionText.clone().appendTo.letsChat; return false;
document.querySelector('.composition-text').clone().appendTo(document.querySelector('.lets-chat'));
letsChat.style.background='#00BCD4';
letsChatButton.style.display='none';
}
else if (letsChatButton.style.display='none' || window.matchMedia("(orientation: portrait)").matches){
compositionArrow.style.transform='rotate(180deg)';
letsChat.style.background='#ff8f00';
letsChatButton.style.display='flex';
}
}
example can be found below: (you may have to play with window
artpenleystudios.com
Here's something that demonstrates part of what you asked. It doesn't take into account orientation change, but it handles the click part. As far as I know, there's no straightforward way to detect orientation change, but here's an article that talks about a few options. Another idea would be to use jQuery Mobile as it fires orientationchange events.
So after much back and forth and after looking at your site more closely, this is what I managed to cobble together.
jQuery('#compositionArrow').click(function() {
var $letsChat = jQuery('.lets-chat');
var letsChat = $letsChat[0];
var letsChatButton = $letsChat.find('a')[0];
// Remove old composition text if it exists.
$letsChat.find('.composition-text').remove();
if (letsChatButton.style.display !== 'none' && window.matchMedia("(orientation: landscape)").matches) {
this.style.transform = 'rotate(180deg)';
$letsChat.append(jQuery('.composition-text').clone());
letsChat.style.background = '#00BCD4';
letsChatButton.style.display = 'none';
}
else if (letsChatButton.style.display === 'none' || window.matchMedia("(orientation: portrait)").matches) {
this.style.transform = '';
letsChat.style.background = '#ff8f00';
letsChatButton.style.display = 'flex';
}
});
It works for me in FireFox on a downloaded version of your site.
Cheers!

Detect whether the intent of a user is to tap or to scroll up/down the page on tactile device

If a user taps (touchstart) outside a popup-div, I want to hide the popup.
But if the user's intent is to scroll/swipe (touchmove), I don't want to hide the popup.
How could the code look like to detect and respond to those two actions (with or without jQuery)?
Here is a basic example of how you could do this:
http://jsfiddle.net/4CrES/2/
The logic behind it involves detecting the initial touch time and saving it to a var
touchTime = new Date();
In the touchend handler subtract this time from the current time to get the difference:
var diff = new Date() - touchTime;
Use an if statement to decide whether the touch duration was short enough to consider it a tap, or long enough to consider it a drag.
if (diff < 100){
//It's a tap
}
else {
//Not a quick tap
}
You could write a more robust implementation by doing a similar difference of the initial touch y position to the final touch y position in the handlers. Another option is to compare the scrollTop of the scrolling area to see if it has been scrolled.
Since click events do not bubble up the DOM on mobile Safari while touch events and custom events do, I recently wrote some code to detect a quick-tap.
It's a quick-tap when
The touch event starts and ends without any movement along the screen
No scrolling occurrs
It all happens in less than 200ms.
If the touch is determined to be a 'quickTap', the TouchManager causes the touched element in the DOM to emit a custom "quickTap" event which then bubbles up the DOM to any other elements that happen to be listening for it. This code defines and creates the touch manager and it will be ready to go immediately
Drawbacks:
Uses jQuery
Only designed with one finger in mind.
also borrowed some code from modernizr. (You can omit that bit if you already include Modernizr.)
Maybe this is overkill, but it's part of a larger codebase I'm working on.
/**
* Click events do not bubble up the DOM on mobile Safari unless the click happens on a link or form input, but other events do bubble up.
* The quick-tap detects the touch-screen equivalent of a click and triggers a custom event on the target of the tap which will bubble up the DOM.
* A touch is considered a click if there is a touch and release without any movement along the screen or any scrolling.
*/
var qt = (function ($) {
/**
* Modernizr 3.0.0pre (Custom Build) | MIT
* Modernizr's touchevent test
*/
var touchSupport = (function() {
var bool,
prefixes = ' -webkit- -moz- -o- -ms- '.split(' ')
if(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) {
bool = true;
} else {
var query = ['#media (',prefixes.join('touch-enabled),('),'heartz',')','{#modernizr{top:9px;position:absolute}}'].join('');
testStyles(query, function( node ) {
bool = node.offsetTop === 9;
});
}
return bool;
}()),
MobileTapEvent = 'tapEvent';
if(touchSupport) {
/* Create a new qt (constructor)*/
var startTime = null,
startTouch = null,
isActive = false,
scrolled = false;
/* Constructor */
function qt() {
var _qt = this,
context = $(document);
context.on("touchstart", function (evt) {
startTime = evt.timeStamp;
startTouch = evt.originalEvent.touches.item(0);
isActive = true;
scrolled = false;
})
context.on("touchend", function (evt) {
window.ct = evt.originalEvent['changedTouches'];
// Get the distance between the initial touch and the point where the touch stopped.
var duration = evt.timeStamp - startTime,
movement = _qt.getMovement(startTouch, evt.originalEvent['changedTouches'].item(0)),
isTap = !scrolled && movement < 5 && duration < 200;
if (isTap) {
$(evt.target).trigger('quickTap', evt);
}
})
context.on('scroll mousemove touchmove', function (evt) {
if ((evt.type === "scroll" || evt.type === 'mousemove' || evt.type === 'touchmove') && isActive && !scrolled) {
scrolled = true;
}
});
}
/* Calculate the movement during the touch event(s)*/
qt.prototype.getMovement = function (s, e) {
if(!s || !e) return 0;
var dx = e.screenX - s.screenX,
dy = e.screenY - s.screenY;
return Math.sqrt((dx * dx) + (dy * dy));
};
return new qt();
}
}(jQuery));
To use the code you would add it to your page then just listen for the quickTap event.
<script type="text/javascript" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script type="text/javascript" src="quick-tap.js"></script>
<script type="text/javascript">
$(document).on('quickTap', function(evt, originalEvent) {
console.log('tap event detected on: ', evt.target.nodeName, 'tag');
});
</script>
evt is the quickTap event.
evt.target is the tapped DOM element (not the jQuery object).
originalEvent is the touchend event where qt determines whether it was a tap or not.
You can hide the popup-div on touchend event.
In touchstart event you remember window.scrollY.
In touchend event, if scrollY positions differ the user has scrolled.

How to disable scrolling in outer elements?

I have a vertically-scrolling div within a page that also scrolls vertically.
When the child div is scrolled with the mouse wheel and reaches the top or bottom of the scroll bar, the page (body) begins to scroll. While the mouse is over the child div, I'd like the page (body) scroll to be locked.
This SO post (scroll down to the selected answer) demonstrates the problem well.
This SO question is essentially the same as mine, but the selected answer causes my page contents to noticeably shift horizontally as the scrollbar disappears and reappears.
I thought there might be a solution that leverages event.stopPropagation(), but couldn't get anything to work. In ActionScript, this kind of thing would be solved by placing a mousewheel handler on the child div that calls stopPropagation() on the event before it reaches the body element. Since JS and AS are both ECMAScript languages, I thought the concept might translate, but it didn't seem to work.
Is there a solution that keeps my page contents from shifting around? Most likely using stopPropagation rather than a CSS fix? JQuery answers are welcome as is pure JS.
here's what i ended up with. very similar to #mrtsherman's answer here, only pure JS events instead of jQuery. i still used jQuery for selecting and moving the child div around, though.
// earlier, i have code that references my child div, as childDiv
function disableWindowScroll () {
if (window.addEventListener) {
window.addEventListener("DOMMouseScroll", onChildMouseWheel, false);
}
window.onmousewheel = document.onmousewheel = onChildMouseWheel;
}
function enableWindowScroll () {
if (window.removeEventListener) {
window.removeEventListener("DOMMouseScroll", onArticleMouseWheel, false);
}
window.onmousewheel = document.onmousewheel = null;
}
function onChildMouseWheel (event) {
var scrollTgt = 0;
event = window.event || event;
if (event.detail) {
scrollTgt = -40 * event.detail;
} else {
scrollTgt = event.wheelDeltaY;
}
if (scrollTgt) {
preventDefault(event);
$(childDiv).scrollTop($(childDiv).scrollTop() - scrollTgt);
}
}
function preventDefault (event) {
event = event || window.event;
if (event.preventDefault) {
event.preventDefault();
}
event.returnValue = false;
}
i've noticed the scrolling doesn't match normal scrolling exactly; it seems to scroll a bit faster than without this code. i assume i can fix by knocking down wheelDeltaY a bit, but it's odd that it would be reported differently by javascript than it's actually implemented by the browser...
I usually do it with a small hack listening to the scroll event on the document: it resets the scroll height back to the original one - effectively freezing the document from scrolling but any inner element with overflow: auto will still scroll nicely:
var scrollTop = $(document).scrollTop();
$(document).on('scroll.scrollLock', function() {
$(document).scrollTop(scrollTop);
});
and then when I'm done with the inner scroll lock:
$(document).off('scroll.scrollLock');
the .scrollLock event namespace makes sure I'm not messing with any other event listeners on scroll.
Although this is an old question, here is how I do it with jQuery. This allows you to scroll a list within an outer list, or you can change the outer list to the document to do what the OP asked.
window.scrollLockHolder = null;
function lockScroll(id){
if (window.scrollLockHolder == null){
window.scrollLockHolder = $('#' + id).scrollTop();
}
$('#' + id).on('scroll', function(){
$('#' + id).scrollTop(window.scrollLockHolder);
});
}
function unlockScroll(id){
$('#' + id).off('scroll');
window.scrollLockHolder = null;
}
And you can use it like this:
<ul onmousemove="lockScroll('outer-scroller-id')" onmouseout="unlockScroll('outer-scroller-id')">
<li>...</li>
<li>...</li>
</ul>
what about this:
div.onmousemove = function() { // may be onmouseover also works fine
document.body.style.overflow = "hidden";
document.documentElement.style.overflow = "hidden";
};
div.onmouseout = function() {
document.body.style.overflow = "auto";
document.documentElement.style.overflow = "auto";
};

How do I scroll to an element using JavaScript?

I am trying to move the page to a <div> element.
I have tried the next code to no avail:
document.getElementById("divFirst").style.visibility = 'visible';
document.getElementById("divFirst").style.display = 'block';
scrollIntoView works well:
document.getElementById("divFirst").scrollIntoView();
full reference in the MDN docs:
https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollIntoView
You can use an anchor to "focus" the div. I.e:
<div id="myDiv"></div>
and then use the following javascript:
// the next line is required to work around a bug in WebKit (Chrome / Safari)
location.href = "#";
location.href = "#myDiv";
For Chrome and Firefox
I've been looking a bit into this and I figured this one out which somehow feels like the most natural way to do it. Of course, this is my personal favorite scroll now. :)
const y = element.getBoundingClientRect().top + window.scrollY;
window.scroll({
top: y,
behavior: 'smooth'
});
For IE, Edge and Safari supporters
Note that window.scroll({ ...options }) is not supported on IE, Edge and Safari. In that case it's most likely best to use
element.scrollIntoView(). (Supported on IE 6). You can most likely (read: untested) pass in options without any side effects.
These can of course be wrapped in a function that behaves according to which browser is being used.
The best, shortest answer that what works even with animation effects:
var scrollDiv = document.getElementById("myDiv").offsetTop;
window.scrollTo({ top: scrollDiv, behavior: 'smooth'});
If you have a fixed nav bar, just subtract its height from top value, so if your fixed bar height is 70px, line 2 will look like:
window.scrollTo({ top: scrollDiv-70, behavior: 'smooth'});
Explanation:
Line 1 gets the element position
Line 2 scroll to element position; behavior property adds a smooth animated effect
We can implement by 3 Methods:
Note:
"automatic-scroll" => The particular element
"scrollable-div" => The scrollable area div
Method 1:
document.querySelector('.automatic-scroll').scrollIntoView({
behavior: 'smooth'
});
Method 2:
location.href = "#automatic-scroll";
Method 3:
$('#scrollable-div').animate({
scrollTop: $('#automatic-scroll').offset().top - $('#scrollable-div').offset().top +
$('#scrollable-div').scrollTop()
})
Important notice: method 1 & method 2 will be useful if the scrollable area height is "auto". Method 3 is useful if we using the scrollable area height like "calc(100vh - 200px)".
You can set focus to element. It works better than scrollIntoView
node.setAttribute('tabindex', '-1')
node.focus()
node.removeAttribute('tabindex')
Try this:
var divFirst = document.getElementById("divFirst");
divFirst.style.visibility = 'visible';
divFirst.style.display = 'block';
divFirst.tabIndex = "-1";
divFirst.focus();
e.g #:
http://jsfiddle.net/Vgrey/
Here's a function that can include an optional offset for those fixed headers. No external libraries needed.
function scrollIntoView(selector, offset = 0) {
window.scroll(0, document.querySelector(selector).offsetTop - offset);
}
You can grab the height of an element using JQuery and scroll to it.
var headerHeight = $('.navbar-fixed-top').height();
scrollIntoView('#some-element', headerHeight)
Update March 2018
Scroll to this answer without using JQuery
scrollIntoView('#answer-44786637', document.querySelector('.top-bar').offsetHeight)
To scroll to a given element, just made this javascript only solution below.
Simple usage:
EPPZScrollTo.scrollVerticalToElementById('signup_form', 20);
Engine object (you can fiddle with filter, fps values):
/**
*
* Created by Borbás Geri on 12/17/13
* Copyright (c) 2013 eppz! development, LLC.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
var EPPZScrollTo =
{
/**
* Helpers.
*/
documentVerticalScrollPosition: function()
{
if (self.pageYOffset) return self.pageYOffset; // Firefox, Chrome, Opera, Safari.
if (document.documentElement && document.documentElement.scrollTop) return document.documentElement.scrollTop; // Internet Explorer 6 (standards mode).
if (document.body.scrollTop) return document.body.scrollTop; // Internet Explorer 6, 7 and 8.
return 0; // None of the above.
},
viewportHeight: function()
{ return (document.compatMode === "CSS1Compat") ? document.documentElement.clientHeight : document.body.clientHeight; },
documentHeight: function()
{ return (document.height !== undefined) ? document.height : document.body.offsetHeight; },
documentMaximumScrollPosition: function()
{ return this.documentHeight() - this.viewportHeight(); },
elementVerticalClientPositionById: function(id)
{
var element = document.getElementById(id);
var rectangle = element.getBoundingClientRect();
return rectangle.top;
},
/**
* Animation tick.
*/
scrollVerticalTickToPosition: function(currentPosition, targetPosition)
{
var filter = 0.2;
var fps = 60;
var difference = parseFloat(targetPosition) - parseFloat(currentPosition);
// Snap, then stop if arrived.
var arrived = (Math.abs(difference) <= 0.5);
if (arrived)
{
// Apply target.
scrollTo(0.0, targetPosition);
return;
}
// Filtered position.
currentPosition = (parseFloat(currentPosition) * (1.0 - filter)) + (parseFloat(targetPosition) * filter);
// Apply target.
scrollTo(0.0, Math.round(currentPosition));
// Schedule next tick.
setTimeout("EPPZScrollTo.scrollVerticalTickToPosition("+currentPosition+", "+targetPosition+")", (1000 / fps));
},
/**
* For public use.
*
* #param id The id of the element to scroll to.
* #param padding Top padding to apply above element.
*/
scrollVerticalToElementById: function(id, padding)
{
var element = document.getElementById(id);
if (element == null)
{
console.warn('Cannot find element with id \''+id+'\'.');
return;
}
var targetPosition = this.documentVerticalScrollPosition() + this.elementVerticalClientPositionById(id) - padding;
var currentPosition = this.documentVerticalScrollPosition();
// Clamp.
var maximumScrollPosition = this.documentMaximumScrollPosition();
if (targetPosition > maximumScrollPosition) targetPosition = maximumScrollPosition;
// Start animation.
this.scrollVerticalTickToPosition(currentPosition, targetPosition);
}
};
Similar to #caveman's solution
const element = document.getElementById('theelementsid');
if (element) {
window.scroll({
top: element.scrollTop,
behavior: 'smooth',
})
}
A method i often use to scroll a container to its contents.
/**
#param {HTMLElement} container : element scrolled.
#param {HTMLElement} target : element where to scroll.
#param {number} [offset] : scroll back by offset
*/
var scrollAt=function(container,target,offset){
if(container.contains(target)){
var ofs=[0,0];
var tmp=target;
while (tmp!==container) {
ofs[0]+=tmp.offsetWidth;
ofs[1]+=tmp.offsetHeight;
tmp=tmp.parentNode;
}
container.scrollTop = Math.max(0,ofs[1]-(typeof(offset)==='number'?offset:0));
}else{
throw('scrollAt Error: target not found in container');
}
};
if your whish to override globally, you could also do :
HTMLElement.prototype.scrollAt=function(target,offset){
if(this.contains(target)){
var ofs=[0,0];
var tmp=target;
while (tmp!==this) {
ofs[0]+=tmp.offsetWidth;
ofs[1]+=tmp.offsetHeight;
tmp=tmp.parentNode;
}
container.scrollTop = Math.max(0,ofs[1]-(typeof(offset)==='number'?offset:0));
}else{
throw('scrollAt Error: target not found in container');
}
};
If you simply want to scroll to the bottom of a list that is inside a div, you can do this.
<body>
<div class="container">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
<div class="box">5</div>
<div class="box">6</div>
<div class="box">7</div>
<div class="box">8</div>
<div class="box">9</div>
</div>
<button>Scroll To</button>
<script>
const btn = document.querySelector("button");
const container = document.querySelector(".container");
btn.addEventListener("click",()=>{
const toplast = document.querySelector(".container").lastElementChild;
toplast.scrollIntoView();
})
</script>
</body>
example output
Focus can be set on interactive elements only... Div only represent a logical section of the page.
Perhaps you can set the borders around div or change it's color to simulate a focus. And yes Visiblity is not focus.
Due to behavior "smooth" doesn't work in Safari, Safari ios, Explorer. I usually write a simple function utilizing requestAnimationFrame
(function(){
var start;
var startPos = 0;
//Navigation scroll page to element
function scrollTo(timestamp, targetTop){
if(!start) start = timestamp
var runtime = timestamp - start
var progress = Math.min(runtime / 700, 1)
window.scroll(0, startPos + (targetTop * progress) )
if(progress >= 1){
return;
}else {
requestAnimationFrame(function(timestamp){
scrollTo(timestamp, targetTop)
})
}
};
navElement.addEventListener('click', function(e){
var target = e.target //or this
var targetTop = _(target).getBoundingClientRect().top
startPos = window.scrollY
requestAnimationFrame(function(timestamp){
scrollTo(timestamp, targetTop)
})
}
})();
I think that if you add a tabindex to your div, it will be able to get focus:
<div class="divFirst" tabindex="-1">
</div>
I don't think it's valid though, tabindex can be applied only to a, area, button, input, object, select, and textarea. But give it a try.
You can't focus on a div. You can only focus on an input element in that div. Also, you need to use element.focus() instead of display()
After looking around a lot, this is what finally worked for me:
Find/locate div in your dom which has scroll bar.
For me, it looked like this :
"div class="table_body table_body_div" scroll_top="0" scroll_left="0" style="width: 1263px; height: 499px;"
I located it with this xpath : //div[#class='table_body table_body_div']
Used JavaScript to execute scrolling like this :
(JavascriptExecutor) driver).executeScript("arguments[0].scrollLeft = arguments[1];",element,2000);
2000 is the no of pixels I wanted to scroll towards the right.
Use scrollTop instead of scrollLeft if you want to scroll your div down.
Note : I tried using scrollIntoView but it didn't work properly because my webpage had multiple divs. It will work if you have only one main window where focus lies.
This is the best solution I have come across if you don't want to use jQuery which I didn't want to.
In case you want to use html, you could just use this:
a href="samplewebsite.com/subdivision.html#id
and make it an html link to the specific element id. Its basically getElementById html version.
try this function
function navigate(divId) {
$j('html, body').animate({ scrollTop: $j("#"+divId).offset().top }, 1500);
}
Pass the div id as parameter it will work I am using it already

javascript: detect scroll end

I have a div layer with overflow set to scroll.
When scrolled to the bottom of the div, I wanna run a function.
The accepted answer was fundamentally flawed, it has since been deleted. The correct answer is:
function scrolled(e) {
if (myDiv.offsetHeight + myDiv.scrollTop >= myDiv.scrollHeight) {
scrolledToBottom(e);
}
}
Tested this in Firefox, Chrome and Opera. It works.
I could not get either of the above answers to work so here is a third option that works for me! (This is used with jQuery)
if (($(window).innerHeight() + $(window).scrollTop()) >= $("body").height()) {
//do stuff
}
Hope this helps anyone!
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight)
{
//your code here
}
I too searched it and even after checking all comments here and more,
this is the solution to check if reached the bottom or not.
OK Here is a Good And Proper Solution
You have a Div call with an id="myDiv"
so the function goes.
function GetScrollerEndPoint()
{
var scrollHeight = $("#myDiv").prop('scrollHeight');
var divHeight = $("#myDiv").height();
var scrollerEndPoint = scrollHeight - divHeight;
var divScrollerTop = $("#myDiv").scrollTop();
if(divScrollerTop === scrollerEndPoint)
{
//Your Code
//The Div scroller has reached the bottom
}
}
This worked for me:
$(window).scroll(function() {
buffer = 40 // # of pixels from bottom of scroll to fire your function. Can be 0
if ($(".myDiv").prop('scrollHeight') - $(".myDiv").scrollTop() <= $(".myDiv").height() + buffer ) {
doThing();
}
});
Must use jQuery 1.6 or higher
I found an alternative that works.
None of these answers worked for me (currently testing in FireFox 22.0), and after a lot of research I found, what seems to be, a much cleaner and straight forward solution.
Implemented solution:
function IsScrollbarAtBottom() {
var documentHeight = $(document).height();
var scrollDifference = $(window).height() + $(window).scrollTop();
return (documentHeight == scrollDifference);
}
Resource: http://jquery.10927.n7.nabble.com/How-can-we-find-out-scrollbar-position-has-reached-at-the-bottom-in-js-td145336.html
Regards
I created a event based solution based on Bjorn Tipling's answer:
(function(doc){
'use strict';
window.onscroll = function (event) {
if (isEndOfElement(doc.body)){
sendNewEvent('end-of-page-reached');
}
};
function isEndOfElement(element){
//visible height + pixel scrolled = total height
return element.offsetHeight + element.scrollTop >= element.scrollHeight;
}
function sendNewEvent(eventName){
var event = doc.createEvent('Event');
event.initEvent(eventName, true, true);
doc.dispatchEvent(event);
}
}(document));
And you use the event like this:
document.addEventListener('end-of-page-reached', function(){
console.log('you reached the end of the page');
});
BTW: you need to add this CSS for javascript to know how long the page is
html, body {
height: 100%;
}
Demo: http://plnkr.co/edit/CCokKfB16iWIMddtWjPC?p=preview
This will actually be the correct answer:
function scrolled(event) {
const container = event.target.body
const {clientHeight, scrollHeight, scrollY: scrollTop} = container
if (clientHeight + scrollY >= scrollHeight) {
scrolledToBottom(event);
}
}
The reason for using the event is up-to-date data, if you'll use a direct reference to the div you'll get outdated scrollY and will fail to detect the position correctly.
additional way is to wrap it in a setTimeout and wait till the data updates.
Take a look at this example: MDN Element.scrollHeight
I recommend that check out this example: stackoverflow.com/a/24815216... which implements a cross-browser handling for the scroll action.
You may use the following snippet:
//attaches the "scroll" event
$(window).scroll(function (e) {
var target = e.currentTarget,
scrollTop = target.scrollTop || window.pageYOffset,
scrollHeight = target.scrollHeight || document.body.scrollHeight;
if (scrollHeight - scrollTop === $(target).innerHeight()) {
console.log("► End of scroll");
}
});
Since innerHeight doesn't work in some old IE versions, clientHeight can be used:
$(window).scroll(function (e){
var body = document.body;
//alert (body.clientHeight);
var scrollTop = this.pageYOffset || body.scrollTop;
if (body.scrollHeight - scrollTop === parseFloat(body.clientHeight)) {
loadMoreNews();
}
});
To do the same in React/JSX, here is the snippet.
export const scrolledToEnd = event => {
const container = event.target;
if (container.offsetHeight + container.scrollTop >= container.scrollHeight) {
return true;
}
return false;
};
And in your component add
<Component onScroll={scrolledToEnd}>
There is experimental onscrollend event https://developer.mozilla.org/en-US/docs/Web/API/Document/scrollend_event
For now works only in firefox 109+, if other browsers catch up will be very nice.
Have polyfill for that https://github.com/argyleink/scrollyfills
Use like
import "scrollyfills";
...
scrollContainer.addEventListener(
"scrollend",
(ev) => { console.log('scroll END') }
);
I found this methode to get the end of the scroll :
let TheBody = document.getElementsByTagName("body"); // I choose the "body" element for my exemple
function OnScrolling(){ // put this on a scrolling EVENT
let ScrollEnd = TheBody[0].scrollHeight - window.innerHeight; // this is the scroll end Pixel
if (ScrollEnd.toFixed() == window.scrollY.toFixed()){
//do stuff
}
}
Okay now for your DIV or any other element that have a scrolling I found this method on JavaScript :
let D = document.getElementById("D1"); // I gave "D1" as id to my div
// this one is to calculate the scroll end Pixels
let Calc = D.scrollHeight - D.clientHeight;
function ScrollingInD1() {
//this one is to calculate the scrolling percent while going through the <div> it can help for "Responsivity"
let percent = (D.scrollTop * 100) / Calc;
if (D.scrollTop == Calc) {
// do Stuffs
}
}

Categories