scroll event not working on mobile - javascript

Setch.me loading normally on desktop but not trigerring on mobile unless if I click on photographers/makeup artists, I've added height=device-height after searching for a solution here but that didn't work.
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() >= $(document).height()) {
track_page++;
load_contents(track_page);
}

Try this:
$(document.body).on('touchmove', onScroll); // for mobile
$(window).on('scroll', onScroll);
// callback
function onScroll(){
if( $(window).scrollTop() + window.innerHeight >= document.body.scrollHeight ) {
track_page++;
load_contents(track_page);
}
}

var addition_constant = 0;
$(document.body).on('touchmove', onScroll); // for mobile
$(window).on('scroll', onScroll);
function onScroll() {
var addition = ($(window).scrollTop() + window.innerHeight);
var scrollHeight = (document.body.scrollHeight - 1);
if (addition > scrollHeight && addition_constant < addition) {
addition_constant = addition;
loadmorecontest();
}
}

The "scrollTop" value must be rounded on mobile devices using "Math.ceil". (It's decimal based on the resolution of the screen), so:
if (el.scrollHeight <= Math.ceil(el.scrollTop) + el.offsetHeight) {
// so something...
}

In addition to previous comments, $(window).scrollTop()
seems not to work on mobile and should be replaced with document.body.scrollTop

It seems bit irrelevant but since I found myself here and my reason that it not worked is the element that I was trying to scroll has;
overflow-y: hidden
When I remove that it worked perfectly. I just wrote that for if it is also someone's case.

Hi you didn't close correctly your event, this should be like this:
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() >= $(document).height()) {
track_page++;
load_contents(track_page);
}});

Related

this "scrollTop" does not work well in firefox only in chrome how can I change it?

scrollTop not working in Firefox
jQuery(window).scroll(function(){
var NextScroll = jQuery(this).scrollTop();
if (NextScroll >= 800){
jQuery('#logomacchia').addClass("maccancello");
} else {
jQuery('#logomacchia').removeClass("maccancello");
}
});
In chrome it works, the class is activated, but in Firefox it does not work, I scroll the page but the class is not added.
Please Use This Code :
jQuery(window).scroll(function(){
if( jQuery(window).scrollTop() >= 800 ) {
jQuery('#logomacchia').addClass("maccancello");
} else {
jQuery('#logomacchia').removeClass("maccancello");
}
});

How to determine scroll direction without actually scrolling

I am coding a page where the first time the user scrolls, it doesn't actually scroll the page down, instead it adds a class with a transition.
I'd like to detect when the user is scrolling down, because if he scrolls up, I want it to do something else.
All the methods that I've found are based on defining the current body ScrollTop, and then comparing with the body scrollTop after the page scrolls, defining the direction, but since the page doesn't actually scroll, the body scrollTop() doesn't change.
animationIsDone = false;
function preventScroll(e) {
e.preventDefault();
e.stopPropagation();
}
$('body').on('mousewheel', function(e) {
if (animationIsDone === false) {
$("#main-header").removeClass("yellow-overlay").addClass("yellow-overlay-darker");
$(".site-info").first().addClass("is-description-visible");
preventScroll(e);
setTimeout(function() {
animationIsDone = true;
}, 1000);
}
});
This is what I have come with, but that way it doesn't matter the direction I scroll it triggers the event
The mousewheel event is quickly becoming obsolete. You should use wheel event instead.
This would also easily allow you to the vertical and/or horizontal scroll direction without scroll bars.
This event has support in all current major browsers and should remain the standard far into the future.
Here is a demo:
window.addEventListener('wheel', function(event)
{
if (event.deltaY < 0)
{
console.log('scrolling up');
document.getElementById('status').textContent= 'scrolling up';
}
else if (event.deltaY > 0)
{
console.log('scrolling down');
document.getElementById('status').textContent= 'scrolling down';
}
});
<div id="status"></div>
Try This using addEventListener.
window.addEventListener('mousewheel', function(e){
wDelta = e.wheelDelta < 0 ? 'down' : 'up';
console.log(wDelta);
});
Demo
Update:
As mentioned in one of the answers, the mousewheel event is depreciated. You should use the wheel event instead.
I know this post is from 5 years ago but I didn't see any good Jquery answer (the .on('mousewheel') doesn't work for me...)
Simple answer with jquery, and use window instead of body to be sure you are taking scroll event :
$(window).on('wheel', function(e) {
var scroll = e.originalEvent.deltaY < 0 ? 'up' : 'down';
console.log(scroll);
});
Try using e.wheelDelta
var animationIsDone = false, scrollDirection = 0;
function preventScroll(e) {
e.preventDefault();
e.stopPropagation();
}
$('body').on('mousewheel', function(e) {
if (e.wheelDelta >= 0) {
console.log('Scroll up'); //your scroll data here
}
else {
console.log('Scroll down'); //your scroll data here
}
if (animationIsDone === false) {
$("#main-header").removeClass("yellow-overlay").addClass("yellow-overlay-darker");
$(".site-info").first().addClass("is-description-visible");
preventScroll(e);
setTimeout(function() {
animationIsDone = true;
}, 1000);
}
});
Note: remember that MouseWheel is deprecated and not supported in FireFox
this one work in react app
<p onWheel={this.onMouseWheel}></p>
after add event listener, in function u can use deltaY To capture mouse Wheel
onMouseWheel = (e) => {
e.deltaY > 0
? console.log("Down")
: console.log("up")
}
Tested on chrome and
$('body').on('mousewheel', function(e) {
if (e.originalEvent.deltaY >= 0) {
console.log('Scroll up'); //your scroll data here
}
else {
console.log('Scroll down'); //your scroll data here
}
});

Detect div scroll bar hit the top

how to detect when div scroll bar, scroll up and hit the top(only when it hit the top)
I have found another post, but this one is hit the bottom.
what i need is hit the top. anyone know how to change this?
$("#divID").scroll(function(){
if($(this)[0].scrollHeight - $(this).scrollTop() <= $(this).outerHeight())
{
alert(1);
}
});
Know when vertical scrollbar hits bottom of scroll in div
working fiddle
var el = $('.test');
el.on('scroll', function(){
if(el.scrollTop() == 0){alert("i just hit the top")}
});
scrollTop will be 0 when the scroll bar is that the top. Try this:
$("#divID").scroll(function () {
if ($(this).scrollTop() == 0) {
alert(1);
}
});
Example fiddle
$("#divID").scroll(function(){
if($(this)[0].scrollHeight - $(this).scrollTop() <= $(this).outerHeight())
{
alert("Bottom");
}
if($(this).scrollTop() == 0)
{
alert("Top");
}
});
Fiddle is here

Prevent scrollTop from calling scroll event

I'm trying to create this behavior: when user scrolls a mousewheel (or presses ↓) the webpage is scrolled down by the height of the window.
I've ended up with following code:
var newScrollTop,
oldScrollTop = $(window).scrollTop(),
preventScroll = false;
$(window).scroll(function() {
if (!preventScroll) {
preventScroll = true;
newScrollTop = $(this).scrollTop();
if (newScrollTop > oldScrollTop) {
$(this).scrollTop( oldScrollTop + $(window).height() );
}
else {
$(this).scrollTop( oldScrollTop - $(window).height() );
}
oldScrollTop = newScrollTop;
preventScroll = false;
}
});
But this doesn't work as I expect it: on scroll event page is scrolled to the very edge (bottom or top). What am I missing?
The issue is you're using scrollTop() which trigger a scroll event inside the window scroll event itself.
So basically, with the code you've written you run into an infinite loop because as soon as the first scroll event is triggered another one is triggered by scrollTop() while your preventScroll variable is still not set to false and so on.
To make your code work you would have to set your preventScroll variable to false inside the setTimeout function like so :
var newScrollTop,
oldScrollTop = $(window).scrollTop(),
preventScroll = false;
$(window).scroll(function() {
if (!preventScroll) {
preventScroll = true;
newScrollTop = $(this).scrollTop();
if (newScrollTop > oldScrollTop) {
$(this).scrollTop( oldScrollTop + $(window).height() );
}
else {
$(this).scrollTop( oldScrollTop - $(window).height() );
}
oldScrollTop = newScrollTop;
setTimeout(function(){ preventScroll = false; }, 0);
}
});
We add some "delay" before we set preventScroll to false.
This way when you call scrollTop() preventScroll variable will still be set to true !
Here's a working fiddle : http://jsfiddle.net/J6Fcm/ (I modified a little bit your code to let the scrolling steps work as expected)
There is no easy way of overriding the default browser scroll functionality. Here's one way of doing what you want, but it requires Brandon Aaron's jquery-mousewheel plugin to manage the mouse scrollwheel:
$(function() {
// Ugly hack to disable browser scrolling (downside: hides scrollbar!!!)
$('html').css('overflow', 'hidden');
// Get viewport height by which to scroll (up or down)
var viewportHeight = $(window).height();
// Recache viewport height on browser resize
$(window).on('resize', function() {
viewportHeight = $(window).height();
});
// Scroll on mousewheel
$('html').on('mousewheel', function(event, delta, deltaX, deltaY) {
// scroll down
if (deltaY < 0)
window.scrollBy(0, viewportHeight);
// scroll up
else
window.scrollBy(0, -viewportHeight);
});
// Disable document keypress event
// which would scroll the content even with "overlow: hidden"
$(document).on('keypress', function(){
return false;
});
// Scroll on arrow up/down keys
$(document).on('keydown', function(event){
// arrow down key
if (event.which == 40)
window.scrollBy(0, viewportHeight);
// arrow up key
if (event.which == 38)
window.scrollBy(0, -viewportHeight);
});
});
Here's a fiddle to demo the code. It all works very well except there is one ugly drawback to my solution. The $('html').css('overflow', 'hidden'); is removing the browser scrollbar.

Get mouse wheel events in jQuery?

Is there a way to get the mouse wheel events (not talking about scroll events) in jQuery?
​$(document).ready(function(){
$('#foo').bind('mousewheel', function(e){
if(e.originalEvent.wheelDelta /120 > 0) {
console.log('scrolling up !');
}
else{
console.log('scrolling down !');
}
});
});
Binding to both mousewheel and DOMMouseScroll ended up working really well for me:
$(window).bind('mousewheel DOMMouseScroll', function(event){
if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) {
// scroll up
}
else {
// scroll down
}
});
This method is working in IE9+, Chrome 33, and Firefox 27.
Edit - Mar 2016
I decided to revisit this issue since it's been a while. The MDN page for the scroll event has a great way of retrieving the scroll position that makes use of requestAnimationFrame, which is highly preferable to my previous detection method. I modified their code to provide better compatibility in addition to scroll direction and position:
(function() {
var supportOffset = window.pageYOffset !== undefined,
lastKnownPos = 0,
ticking = false,
scrollDir,
currYPos;
function doSomething(scrollPos, scrollDir) {
// Your code goes here...
console.log('scroll pos: ' + scrollPos + ' | scroll dir: ' + scrollDir);
}
window.addEventListener('wheel', function(e) {
currYPos = supportOffset ? window.pageYOffset : document.body.scrollTop;
scrollDir = lastKnownPos > currYPos ? 'up' : 'down';
lastKnownPos = currYPos;
if (!ticking) {
window.requestAnimationFrame(function() {
doSomething(lastKnownPos, scrollDir);
ticking = false;
});
}
ticking = true;
});
})();
See the Pen Vanilla JS Scroll Tracking by Jesse Dupuy (#blindside85) on CodePen.
This code is currently working in Chrome v50, Firefox v44, Safari v9, and IE9+
References:
https://developer.mozilla.org/en-US/docs/Web/Events/scroll
https://developer.mozilla.org/en-US/docs/Web/Events/wheel
As of now in 2017, you can just write
$(window).on('wheel', function(event){
// deltaY obviously records vertical scroll, deltaX and deltaZ exist too.
// this condition makes sure it's vertical scrolling that happened
if(event.originalEvent.deltaY !== 0){
if(event.originalEvent.deltaY < 0){
// wheeled up
}
else {
// wheeled down
}
}
});
Works with current Firefox 51, Chrome 56, IE9+
There's a plugin that detects up/down mouse wheel and velocity over a region.
Answers talking about "mousewheel" event are refering to a deprecated event. The standard event is simply "wheel". See https://developer.mozilla.org/en-US/docs/Web/Reference/Events/wheel
This worked for me:)
//Firefox
$('#elem').bind('DOMMouseScroll', function(e){
if(e.originalEvent.detail > 0) {
//scroll down
console.log('Down');
}else {
//scroll up
console.log('Up');
}
//prevent page fom scrolling
return false;
});
//IE, Opera, Safari
$('#elem').bind('mousewheel', function(e){
if(e.originalEvent.wheelDelta < 0) {
//scroll down
console.log('Down');
}else {
//scroll up
console.log('Up');
}
//prevent page fom scrolling
return false;
});
from stackoverflow
Here is a vanilla solution. Can be used in jQuery if the event passed to the function is event.originalEvent which jQuery makes available as property of the jQuery event. Or if inside the callback function under we add before first line: event = event.originalEvent;.
This code normalizes the wheel speed/amount and is positive for what would be a forward scroll in a typical mouse, and negative in a backward mouse wheel movement.
Demo: http://jsfiddle.net/BXhzD/
var wheel = document.getElementById('wheel');
function report(ammout) {
wheel.innerHTML = 'wheel ammout: ' + ammout;
}
function callback(event) {
var normalized;
if (event.wheelDelta) {
normalized = (event.wheelDelta % 120 - 0) == -0 ? event.wheelDelta / 120 : event.wheelDelta / 12;
} else {
var rawAmmount = event.deltaY ? event.deltaY : event.detail;
normalized = -(rawAmmount % 3 ? rawAmmount * 10 : rawAmmount / 3);
}
report(normalized);
}
var event = 'onwheel' in document ? 'wheel' : 'onmousewheel' in document ? 'mousewheel' : 'DOMMouseScroll';
window.addEventListener(event, callback);
There is also a plugin for jQuery, which is more verbose in the code and some extra sugar: https://github.com/brandonaaron/jquery-mousewheel
This is working in each IE, Firefox and Chrome's latest versions.
$(document).ready(function(){
$('#whole').bind('DOMMouseScroll mousewheel', function(e){
if(e.originalEvent.wheelDelta > 0 || e.originalEvent.detail < 0) {
alert("up");
}
else{
alert("down");
}
});
});
I was stuck in this issue today and found this code is working fine for me
$('#content').on('mousewheel', function(event) {
//console.log(event.deltaX, event.deltaY, event.deltaFactor);
if(event.deltaY > 0) {
console.log('scroll up');
} else {
console.log('scroll down');
}
});
use this code
knob.bind('mousewheel', function(e){
if(e.originalEvent.wheelDelta < 0) {
moveKnob('down');
} else {
moveKnob('up');
}
return false;
});
The plugin that #DarinDimitrov posted, jquery-mousewheel, is broken with jQuery 3+. It would be more advisable to use jquery-wheel which works with jQuery 3+.
If you don't want to go the jQuery route, MDN highly cautions using the mousewheel event as it's nonstandard and unsupported in many places. It instead says that you should use the wheel event as you get much more specificity over exactly what the values you're getting mean. It's supported by most major browsers.
my combination looks like this. it fades out and fades in on each scroll down/up. otherwise you have to scroll up to the header, for fading the header in.
var header = $("#header");
$('#content-container').bind('mousewheel', function(e){
if(e.originalEvent.wheelDelta > 0) {
if (header.data('faded')) {
header.data('faded', 0).stop(true).fadeTo(800, 1);
}
}
else{
if (!header.data('faded')) header.data('faded', 1).stop(true).fadeTo(800, 0);
}
});
the above one is not optimized for touch/mobile, I think this one does it better for all mobile:
var iScrollPos = 0;
var header = $("#header");
$('#content-container').scroll(function () {
var iCurScrollPos = $(this).scrollTop();
if (iCurScrollPos > iScrollPos) {
if (!header.data('faded')) header.data('faded', 1).stop(true).fadeTo(800, 0);
} else {
//Scrolling Up
if (header.data('faded')) {
header.data('faded', 0).stop(true).fadeTo(800, 1);
}
}
iScrollPos = iCurScrollPos;
});
If using mentioned jquery mousewheel plugin, then what about to use the 2nd argument of event handler function - delta:
$('#my-element').on('mousewheel', function(event, delta) {
if(delta > 0) {
console.log('scroll up');
}
else {
console.log('scroll down');
}
});
I think many key things are a bit all over the place and I needed to read all the answers to make my code work as I wanted, so I will post my findings in just one place:
You should use "wheel" event over the other deprecated or browser specific events.
Many people here is getting something wrong: the opposite of x>0 is x<=0 and the opposite of x<0 is x>=0, many of the answers in here will trigger scrolling down or up incorrectly when x=0 (horizontal scrolling).
Someone was asking how to put sensitivity on it, for this you can use setTimeout() with like 50 ms of delay that changes some helper flag isWaiting=false and you protect yourself with if(isWaiting) then don't do anything. When it fires you manually change isWaiting=true and just below this line you start the setTimeout again who will later change isWaiting=false after 50 ms.
I got same problem recently where
$(window).mousewheel was returning undefined
What I did was $(window).on('mousewheel', function() {});
Further to process it I am using:
function (event) {
var direction = null,
key;
if (event.type === 'mousewheel') {
if (yourFunctionForGetMouseWheelDirection(event) > 0) {
direction = 'up';
} else {
direction = 'down';
}
}
}

Categories

Resources