Scroll event not working on chrome and not precise in firefox - javascript

I tried to build a custom scroll for my website but it's not perfect and I don't know how to improve it. It should scroll from one position to another specific position but there is a difference of pixels that become bigger every scroll events. It also seems to not work on chrome.
here is a link to the html file :http://infographie.inraci.be/blc/blc.html
here is the code :
$(window).bind('mousewheel DOMMouseScroll', function(event){
var hauteur5 = $(window).height();
var scroll5 = $(window).scrollTop();
if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) {
$(window).scrollTo(scroll5-hauteur5/4,1,function(){
})
} else {
$(window).scrollTo(scroll5+hauteur5/4,1,function(){
})
}
});

If you want check this snippet: https://stackoverflow.com/a/38572744/3605379
There I check the week speed with a timeout. Play with it so you can get the timing right.

Related

On iOS Safari, window.scrollTo doesn't work after orientation change

In short:
In iOS Safari, window.scrollTo method doesn't do anything if called from orientationchange event handler. It seems like a certain amount of time (500-1000ms) must pass before you can modify scroll position after orientation change.
Is there a workaround to change scroll position immediately and avoid the problem when user can see old scroll position for a moment after orientation change?
Detailed problem description:
I need to implement the following feature for mobile browsers:
When the user switches to landscape mode, he should see fullscreen video. When he switches back to portrait, he should be returned to exact same place where he left off.
The second part is the problem. Both iOS and Android will keep scroll position if you switch orientation back and forth, but only if you dont scroll the screen and dont make any adjustments to DOM. So if you just switch from portrait to landscape and back, everything works as expected. If you switch from portrait to landscape, adjust scroll position even by 1 pixel or make any changes to DOM, you will return to a different scroll position.
So I'm trying to pragmatically restore scroll position once the user returns to portrait orientation. Here's the simplified code I use:
var scrollPosition;
var savedScrollPosition;
window.addEventListener('scroll', function() {
scrollPosition = window.scrollY;
});
window.addEventListener('orientationchange', function(event) {
if (Math.abs(window.orientation) === 90) {
// This line will correctly save last scroll position for portrait orientation
savedScrollPosition = scrollPosition;
} else {
// This line will correctly try to restore previously saved scroll position
window.scrollTo(0, savedScrollPosition);
}
});
This works on android, but on iOS it doesn't. The problem is, window.scrollTo just doesn't seem to do anything until the certain time after orientation change has passed.
So if I change
window.scrollTo(0, savedScrollPosition);
to
setTimeout(function() {
window.scrollTo(0, savedScrollPosition);
}, 1000);
it works on iOS, but the user can see wrong portion of the page for a few moments, which leads to a poor user experience.
I was hoping that somebody knows a way to change scroll position on iOS immediately after orientationchage event.
Thank you.
In the end, I was forced to go with the following code:
var scrollPosition;
var savedScrollPosition;
window.addEventListener('scroll', function() {
scrollPosition = window.scrollY;
});
window.addEventListener('orientationchange', function(event) {
if (Math.abs(window.orientation) === 90) {
savedScrollPosition = scrollPosition;
} else {
if (isIOS()) {
var retryScroll = setInterval(function () {
if (window.scrollX === 0 && window.scrollY == savedScrollPosition) {
clearInterval(retryScroll);
} else {
window.scrollTo(0, savedScrollPosition);
}
}, 10 );
} else {
window.scrollTo(0, savedScrollPosition);
}
}
});
The user will see a small visual glitch, but it's still the best solution.

detect (event) attempting to scroll up/down when already at top/bottom of the page with javascript or angularJS,

so i want to detect scrolling to the top(or bottom) when i'm already at the top(or bottom) of the page. I've seen a couple questions with similar problems here, but the only answer was to detect mousewheel event.
but considering the fact that i want to detect it when it's triggered by any similar action (like pressing the up/down key, or mousewheel and touchpad scrolling, or pageUp/Down, or home/end ...) should I create eventlisteners for each and every one of them? does anyone know a better way of doing it??
This is what I have for you so far. I can detect when you hit the top or bottom regardless of how you scrolled. The issue is detecting when you are trying to keep scrolling after you reached it because the scroll event does not fire unless you actually scroll. The only thing I can think of is to programmatically scroll the screen up slightly so that you can scroll again, but I don't recommend doing that. Other than this I don't see any other way other than creating custom events for each possible way the user can scroll.
$(function(){
var lastScrollBarPos = 0;
$(window).scroll(function(event){
var browserViewportHeight = $(window).height();
var hmtlDocHeight = $(document).height();
var scrollBarPos = $(window).scrollTop();
if (scrollBarPos > lastScrollBarPos){
// downscroll code
console.log('scroll down');
if(hmtlDocHeight == browserViewportHeight + scrollBarPos){
console.log('reached bottom');
}
} else {
// upscroll code
console.log('scroll up');
if(scrollBarPos == 0){
//we are at the top and someone is scrolling
console.log('reached top');
}
}
lastScrollBarPos = scrollBarPos;
});
});

Horizontal One-Page Site: Mobile-Webkit Scrolling & Swiping Issues

Here is a basic demo of what I'm working with: http://jsfiddle.net/3N8wY/9/
Issue #1
If you view that link from a stock Android browser, or (more importantly) an iOS device, the website will not scroll. It does this odd fidgety/pulse thing and goes no where. It will sometimes scroll if you choose a link way on down the line, but it never ends up in the right spot.
I believe this has to do with the JS. When I tried it on my phone, I noticed it wasn't hashing the new value of the selected link.
JS
$(document).ready(function () {
$('.main-nav').on('click', function (e) {
e.preventDefault();
var toTarget = $(this).attr('href');
history.pushState(null, null, toTarget);
$(window).triggerHandler('hashchange');
});
});
$(window).on('hashchange', function () {
if(!window.location.hash) return;
var $target = $(window.location.hash);
console.log($target);
$('html, body').stop().animate({
scrollLeft: $target.offset().left,
scrollTop: $target.offset().top
}, 900, 'swing');
});
CREDIT FOR JS - Horizontal One-Page site won't go "backwards" to previous DIV
Issue #2
If you swipe a little left or right, it moves the page. I do not want that. Setting the overflow to hidden has not helped with swiping.
Ideally, if the user swiped enough right or left, it would "snap" the page in the desired direction, and then push the correct hash value. If they didn't swipe enough, it would snap back to the current page.
Having said that, I will be quite happy with it if it just doesn't move at all. I had envisioned that the user would use the menu to navigate, and only be able to scroll up and down.
Somewhat off-topic
Does anyone have a suggestion for a desktop browser that closely emulates the browser in an iOS device? I believe that webkit driving the stock Android browser is very similar, so I think I'd kill two birds here if I could get a hold of that for testing. On another project, I noticed that my desktop version of Safari seemed to deliver very different results than what I'd find on an iOS device (absolutely positioned elements behaved differently with respect to "top/margin-top" in each respective browser).
Thank you very much in advance for reading and contributing! I am extremely appreciative and grateful.
Issue #1
Turns out that I didn't have Modernizr installed correctly (hadn't included the no-js class in the html tag), which once rectified, solved the hashing issue I was running into on some stock Android browsers.
After that was fixed, I still ran into the odd scrolling behavior. Often, the page would scroll to the desired location, but then jump back. Upon further research, I came across this:
Jquery Animate ScrollLeft doesnt work on ipad.
That seemed to fix the undesired scrolling behavior for some of the poor performers, but not on iOS devices. This could have something to do with it, ScrollLeft and ScrollTop on Ipad using animate chain (jQuery), but I've figured out something else that works (will post below).
So far as I can tell, iOS devices (7+) automatically scroll to top BEFORE any scrollLeft animation. I don't have access to any physical devices, but I do have access to an iMac, where I was able to get ahold of the iOS Simulator and observed the unwanted scrolling behavior. I tried unlinking the two scrolling actions (left & top, as most posts will suggest you try), but that didn't make a difference.
It might have had something to do with what I was scrolling (ie the body or the html), I read that in a few posts, but messing with that rendered no useful results.
As I was testing, I realized that by only scrolling left, my script finally functioned "properly".
The interesting bit is that I noticed that the browser would scroll to top AUTOMATICALLY BEFORE horizontally scrolling to my target. So, if they update their code to make scrollLeft function properly, I'll have to go back and add a scrollTop function. For the the time being...
Not exactly a "fix" (the browser behaving inappropriately working to my "benefit", worrisome), but I'll take it.
Issue #2
Just to clarify, it was especially tricky to tackle this one because the page NEEDS to be able to scroll left and right (what with the horizontal layout and all), but only when I want it to.
As far as attempting to disable swiping, I really came up short. The closest I got there was with a plugin called touchSwipe; however, that broke too much (CSS-layout in some mobile browsers), and I couldn't seem to re-enable the tapping of non-link('a') assets.
What I ended up doing is creating a function that would monitor the horizontal scroll position of the window, and reposition the window if it changed. Seems a little buggy in some browsers, but it seems like I'm close to making 'everybody' happy.
EDIT: Changed the function to the much more compliant window.scrollTo(), just had to fetch positions before I fired it. Haven't tested a browser that didn't like it (so far, fingers crossed).
Side note
Lastly, when I got to RWD testing...
I was spoiled with the 'Resize Window' plugin for Chrome, and didn't realize the lackluster availability of working plugins for other browsers. So, I created a testbed full of 20 or so iframes of differing proportions, set to match the most popular device dimensions.
When I got down to mobile device dimensions, I realized that the browser's scrollbar was skewing my proportions. I'd looked into custom scrollbars before, so I delved back into it to attempt to equalize the variable all across the field.
After trying many different plugins, 'nicescroll' was the only one I could get working properly (http://nicescroll.areaaperta.com/). If you're going to use it, be sure to run a mobile test (http://www.detectmobilebrowsers.com/), and only run it on non-mobile devices (admittedly, this script seems to fail at picking up some mobile browsers, but it's better than nothing). All the mobile browsers I tested already had a similar scrollbar in place (by default), so it's completely unnecessary (plus it breaks some mobile browsers).
Working JS
$(document).ready(function() {
var loadedTarget = $(window.location.hash);
function unbindWindow() { $(window).unbind('scroll'); }
function repositionWin() {
unbindWindow();
var targetPosLeft = loadedTarget.offset().left;
$(window).on('scroll', function(e) {
var alteredPosLeft = $(window).scrollLeft();
var alteredPosTop = $(window).scrollTop();
if (alteredPosLeft != targetPosLeft) {
window.scrollTo(targetPosLeft, alteredPosTop),
unbindWindow(), // MAY BE UNNECESSARY, IOS SCARED ME INTO IT, SAME AS BELOW
repositionWin();
}
});
}
function browserResult() {
if (jQuery.browser.mobile === true) {
$('body').css({"overflow-x":"hidden","overflow-y":"scroll"});
repositionWin();
}
else {
setTimeout ((function(){
$("html").niceScroll({
cursorcolor: '#231f20',
cursoropacitymax: '0.5',
scrollspeed: '100',
mousescrollstep: '50'
});
}), 300);
setTimeout (repositionWin, 300);
}
}
browserResult();
$('.main-nav-link').click(function(e) {
e.preventDefault();
var toTarget = $(this).attr('href');
history.pushState(null, null, toTarget);
// CODE SPECIFIC TO PROJECT (NAMELY FLEXSLIDER PAUSE/PLAY STUFF) OMITTED
$(window).triggerHandler('hashchange');
});
});
$(window).on('hashchange', function () {
if(!window.location.hash) return;
var target = $(window.location.hash);
var targetHash = window.location.hash;
var iOS = ( navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? true : false );
var currentPosition = $(window).scrollLeft();
var targetPosLeft = target.offset().left;
var targetPosTop = target.offset().top;
function unbindWindow() { $(window).unbind('scroll'); }
function repositionWin() {
unbindWindow();
$(window).on('scroll', function() {
var alteredPosLeft = $(window).scrollLeft();
var alteredPosTop = $(window).scrollTop();
if (alteredPosLeft != targetPosLeft) {
window.scrollTo(targetPosLeft, alteredPosTop),
unbindWindow(),
repositionWin();
}
});
}
function fadePages() {
if (targetPosLeft == currentPosition) {
}
else {
function fadePageOut() {
$('.page-container').stop(true,false).animate({
opacity: "0.25",
transition: "opacity 0.1s 0.0s ease"
});
}
function fadePageIn() {
$('.page-container').stop(true,false).animate({
opacity: "1.0",
transition: "opacity 0.3s 0.0s ease"
});
}
fadePageOut();
setTimeout (fadePageIn, 900);
}
}
function pageChange() {
if (jQuery.browser.mobile === true) {
if (iOS === true) {
unbindWindow();
$('html,body').stop(true,false).animate({
scrollLeft: targetPosLeft}, 1400);
setTimeout (repositionWin, 1500);
}
else {
unbindWindow();
$('html,body').stop(true,false).animate({
scrollLeft: targetPosLeft}, 1200, function() {
$(this).stop(true,false).animate({
scrollTop: targetPosTop
}, 200, repositionWin);
});
}
}
else {
fadePages();
unbindWindow();
$('html,body').stop(true,false).delay(100).animate({
scrollLeft: targetPosLeft,
scrollTop: targetPosTop
}, 1300, repositionWin);
}
}
// WAITING FOR OTHER ANIMATIONS TO COMPLETE SO THAT MOBILE DEVICES AREN'T TOO OVERLOADED
if ($('#mini-site-menu-button-container').is(':visible') === true && $('#main-menu-wrapper').hasClass('show-main-menu') === true) {
setTimeout (pageChange, 300)
}
if ($('.footer-container').is(':visible') === true) {
setTimeout (pageChange, 500)
}
if ($('.form-instructions-wrapper').hasClass('expand-form-instruct') === true) {
setTimeout (pageChange, 500)
}
if ($('.quick-quote-container').hasClass('toggle-open') === true) {
setTimeout (pageChange, 500)
}
if ($('#mini-site-menu-button-container').is(':visible') === false && $('.footer-container').is(':visible') === false && $('.form-instructions-wrapper').hasClass('expand-form-instruct') === false && $('.quick-quote-container').hasClass('toggle-open') === false) {
pageChange();
}
if ($('#main-menu-wrapper').hasClass('show-main-menu') === false && $('.footer-container').is(':visible') === false && $('.form-instructions-wrapper').hasClass('expand-form-instruct') === false && $('.quick-quote-container').hasClass('toggle-open') === false) {
pageChange();
}
});
Cheers.
I'll update as time goes on, or if I find a better solution to either of the issues. I had zero programming experience actually writing any of my own code (and this isn't all "mine") before this (changing selectors was pretty much the extent of my "skills"), so please excuse any glaring mistakes.

disable scrolling up past specific point

How can I make it so that a viewer cannot scroll up (past a specific point)?
Making it so a viewer cannot scroll is easy with:
body{
overflow: hidden;
}
but that disables scrolling down too.
Detailed description
what I want is some javascript/jquery code that will not allow scrolling up past a given parameter, while the viewer can still scroll up and down before that parameter is reached, but after it is reached they can only scroll up as long as it's not scrolling up past the given parameter
I have absolutely no idea how to go about doing this, any ideas?
You could set a physical point and say something like:
$(function() {
var scrollPoint = 200;
var scrolledPast = false;
$(window).scroll(function() {
$(window).scrollTop() > scrollPoint ? scrolledPast = true : '';
$(window).scrollTop() < scrollPoint && scrolledPast == true ? $(window).scrollTop(scrollPoint) : '';
}).scroll();
});
Fiddle
Although the disabling of scrolling seems a bit counter-intuitive-- why not just hide stuff off the page itself?

Detect Fixed position JavaScript not working in IE

i use YS for fixed position menu, is working fine in firefox but not working in IE.
$(function(){ // this is the shorthand for document.ready
$(document).scroll(function(){ // this is the scroll event for the document
scrolltop = $(document).scrollTop(); // by this we get the value of the scrolltop ie how much scroll has been don by user
if(parseInt(scrolltop) >= 80) // check if the scroll value is equal to the top of navigation
{
$("#navbar").css({"position":"fixed","top":"0"}); // is yes then make the position fixed to top 0
}
else
{
$("#navbar").css({"position":"absolute","top":"80px"}); // if no then make the position to absolute and set it to 80
}
}
}
Any solution fixing this problem for ie?
The problem, to me seems to be that IE doesn't trigger the .scroll event. At least, not in jsfiddle. If you explicitly trigger the event, that does seem to fix things. this fiddle was tested in IE8 and it works. The code:
$(function()
{
$(document).scroll(function()
{//add var here, avoid evil globals:
var scrolltop = $(document).scrollTop();
if(parseInt(scrolltop) >= 80)
{
$("#navbar").css({"position":"fixed","top":"0"});
}
else
{
$("#navbar").css({"position":"absolute","top":"80px"});
}
});//close properly
$(document).scroll();//explicit call
});//close this, too
You are missing ')' in your code working jsfiddle (tested in IE7 and IE9)
$(function(){ // this is the shorthand for document.ready
$(window).scroll(function(){ // this is the scroll event for the document
scrolltop = $(window).scrollTop(); // by this we get the value of the scrolltop ie how much scroll has been don by user
if(parseInt(scrolltop) >= 80) // check if the scroll value is equal to the top of navigation
{
$("#navbar").css({"position":"fixed","top":"0"}); // is yes then make the position fixed to top 0
}
else
{
$("#navbar").css({"position":"absolute","top":"80px"}); // if no then make the position to absolute and set it to 80
}
}); //here
});//here
For position fix must your parent element has this style
position:relative;
best regards

Categories

Resources