Using the mouse wheel to scroll a browser window horizontally - javascript

I have a very wide website, intentionally designed to have no vertical scrolling but a lot of horizontal.
Scrolling horizontally is usually a pain to users so was wondering if there was some way of using the middle mouse or other scrolling habits (eg. page up/down, up/down arrows, middle mouse click/drag) to scroll horizontally instead of vertically.
Edit: The main reason for requiring horizontal scrolling is because the layout/approach is a left to right graphical/interactive timeline. I've since found some examples;
This one with MooTools: http://www.tinkainteractive.com.au/ and a few other examples I found at http://naldzgraphics.net/inspirations/40-examples-of-horizontal-scrolling-websites/

You can add your own event listener
document.onmousewheel = myScrollFunction
Scrolling can be done by
window.scrollBy(x, y)
Where x is the horizontal scrolling offset and y the vertical scrolling offset.
So you might just call this function in your event listener. You may have to stop bubbling with event.stopPropagation and prevent browser default behaviour with event.preventDefault so that the original scrolling behaviour doesn't get applied anymore.
Edit: I was curious about this so I implemented something :-)
function onScroll(event) {
// delta is +120 when scrolling up, -120 when scrolling down
var delta = event.detail ? event.detail * (-120) : event.wheelDelta
// set own scrolling offset, take inverted sign from delta (scroll down should scroll right,
// not left and vice versa
var scrollOffset = 10 * (delta / -120);
// Scroll it
window.scrollBy(scrollOffset, 0);
// Not sure if the following two are necessary, you may have to evaluate this
event.preventDefault;
event.stopPropagation;
}
// The not so funny part... fin the right event for every browser
var mousewheelevt=(/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel";
if (document.attachEvent)
document.attachEvent("on"+mousewheelevt, onScroll);
else if (document.addEventListener)
document.addEventListener(mousewheelevt, onScroll, false);
This works in Firefox 3.5 and Opera 10, however not in IE8. But that would be your part now... ;-)

I wouldn't change this behaviour. It would be very unexpected to the user. Maybe it makes sense to cover the symptom and re-layout your website to switch to a more vertical centered approach?
Still you can do loads of event-handling stuff with java-script, but as said I would rethink the layout.

Related

`window.ScrollTo(...)` in a `mousemove` event gives horrible janky scrolling

I've got a custom scrollbar solution (view on CodePen).
The obvious idea is dragging the custom scrollbar should scroll the page.
Try it and see what happens... it's bizarrely janky, and the scrollbar and page scrolling will suddenly snap between points.
The scrolling process is currently in a mousemove handler:
update the scrollbar position visually
window.scrollTo(...) the new position, calculated as viewport top relative to the new scrollbar position
If I comment out the window.scrollTo(...) line, the scrollbar itself then moves perfectly smoothly and sticks with the cursor.
Pertinent code
mousemove(e) {
if (!this.active) return;
this.update(this.getScrollDeltaPositional(e.pageY));
window.scrollTo({top: this.getWindowScrollTop()});
}
update(position, show=true, timer=true, time=0) {
let track = this.getTrackHeight();
this.trackPosition = Math.min(Math.max(position, 0), track);
this.track.style.transform = `translateY(${this.trackPosition}px)`;
}
getWindowScrollTop() {
let scroll = this.getDocumentScroll();
let position = (this.trackPosition / this.root.clientHeight);
return Math.round(scroll * position);
}
(Recommended you view the full source on CodePen)
I presume the scrolling each mousemove is blocking the mousemove events, resulting in the sudden snaps being observed.
How to achieve a smooth scrolling effect on window using a custom scrollbar?
I finally found the answer
After far too many hours of trying everything conceivable to remedy this, I stumbled upon this identical problem: https://css-tricks.com/forums/topic/scrolltop-inexplicably-going-haywire/.
As that user eventually discovered, MouseEvent.pageY (which is what I was using to get scroll position) is
relative to the top edge of the viewport, including scroll offsets.
Therefore, the scroll movement effectively amplifies the mousemove events, causing the scrolling to accelerate exponentially as seen in the demo.
So after half a day of hacking about with this, the fix is a simple Ctrl+H... use MouseEvent.clientY instead.

Unexpected jump while changing position from absolute to fixed, why?

first of all I want to say that it's not about content jumping!
I have a navbar and a sidebar which both have absolute position. after user scrolls 100 pixels I change both of them to fixed. but an odd action happens (not always!). wrappers of navbar and sidebar flush for a second. I tested it with different browsers and it does not depend on browser. I tried to reproduce the situation in this fiddle:
https://jsfiddle.net/addxmkgj/
(resize the screen as large as possible it happens in large screens)
-- Edit --
https://codepen.io/anon/pen/dJKBPe
codepen link added too.
Causes
Scrolling can generate scroll events quickly and handlers may need to either throttle scroll events to some extent (e.g. perform code action after scrolling has stopped) or be fairly lightweight functions that can execute quickly.
In addition scroll event handling is not synchronized with page update: if the mouse wheel initiates downward scrolling, scrolling can continue after the wheel is released (and similarly with touch event scrolling). The browser can scroll below a top position of 100px before scroll event handling has had a chance to catch up and change the positioning.
The result is the header jumps down from being partially off-screen to occupy a fixed position at top of screen. The faster the scroll action (or the busier the browser is) the more likely it is that jumping will be noticeable.
A secondary effect in desktop browsing is that when the side bar panel scrolls upwards past top of screen and moves down again, a visible patch of white screen "flashes" momentarily below the side bar before fixed positioning takes effect.
Experimental Remedies
Flashing of the side bar can be reduced but not necessarily fully eliminated, by increasing the height of the container. Changing the height to 150% with visible overflow met with some success:
.side-bar {
position: absolute;
height: 150%;
... /* more declarations */
This may or may not conflict with application requirements.
Some mitigation of navbar jumping can be achieved by using requestAnimationFrame call backs to monitor scrollTop values and change positioning as necessary. This does not use scroll event handling as such:
$(document).ready(function() {
$(window).resize(function() {
if( $(window).width() > 850) {
$('.navbar').css('display', 'block');
} else {
$('.navbar').css('display', 'none');
}
});
scrollTo(0, 0);
var num = 100;
var bAbsolute = true;
function checkScroll() {
var newTop = $(window).scrollTop();
if( bAbsolute && newTop >= num) {
$('.navbar').css('position', 'fixed');
$('.navbar').css('top', '0');
$('.side-bar').css('position', 'fixed');
$('.side-bar').css('top', '0');
bAbsolute = false;
}
if( !bAbsolute && newTop < num) {
$('.navbar').css('position', 'absolute');
$('.side-bar').css('position', 'absolute');
$('.navbar').css('top', '100px');
$('.side-bar').css('top', '100px');
bAbsolute = true;
}
requestAnimationFrame( checkScroll);
}
requestAnimationFrame( checkScroll)
});
This code showed an improvement in jump reduction but was not perfect. It is not particularly a JQuery solution and calls requestAnimationFrame directly.
One option, of course, is to do nothing given browser timing constraints.
Update
This MDN guide for Scroll linked effects explains the root cause problem better than I was able to:
most browsers now support some sort of asynchronous scrolling .... the visual scroll position is updated in the compositor thread and is visible to the user before the scroll event is updated in the DOM and fired on the main thread ... This can cause the effect to be laggy, janky, or jittery — in short, something we want to avoid.
So the absolutely positioned elements can scroll off screen (to some extent) before scroll handlers are notified of a new scroll position.
The solution going forward is to use sticky positioning (see the scroll effects guide above or the CSS position guide. However position:sticky swaps between relative and fixed position so the HTML would need redesigning to accommodate this.
Sticky positioning is also leading edge technology at January 2018, and not yet recommended for production use on MDN. A web search for "JQuery support sticky position" revealed a choice of JQuery plugin support.
Recommendation
Potentially the best-case compromise may be to redesign the HTML to use sticky positioning and include a JQuery plugin that uses native support when available or a polyfill when not - site visitors with supporting browsers will get the best experience, those with older browsers will get functional support.

Create a floating horizontal scroll bar for an iFrame

I have an iFrame. If a user zooms in or uses high magnification due to bad eyesight, I want a horizontal scroll bar to appear so that the user can scroll left to right within the iFrame. This part is easy and not an issue. The problem I've found is that the scroll bar appears at the bottom of the iFrame, which, if zoomed in enough to need it, would require the user to scroll very far down from the actual content to use it, which isn't user friendly.
What I want is for a scroll bar to be visible at the bottom of the visible window that is linked to the main scroll bar, and would be a bonus if it disappears if the user does scroll down enough to see the main scroll bar.
I should reiterate that this is inside an iFrame where the content is cross-domain. I can edit the content in the iFrame but it would be a fairly large task to do that, whereas editing the main window is relatively simple, so would be nice if all the work required could be done in there instead.
Another option you have is to control the scroll with the mouse wheel, see example https://jsfiddle.net/DIRTY_SMITH/5gs8pojm/
(function() {
function scrollHorizontally(e) {
e = window.event || e;
var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
document.documentElement.scrollLeft -= (delta*40); // Multiplied by 40
document.body.scrollLeft -= (delta*40); // Multiplied by 40
e.preventDefault();
}
if (window.addEventListener) {
// IE9, Chrome, Safari, Opera
window.addEventListener("mousewheel", scrollHorizontally, false);
// Firefox
window.addEventListener("DOMMouseScroll", scrollHorizontally, false);
} else {
// IE 6/7/8
window.attachEvent("onmousewheel", scrollHorizontally);
}
})();

Any options for position during webkit-overflow-scrolling: touch event

I have a div with webkit-overflow-scrolling set to touch. On iOS this then gives me an updated position during the touchmove event, but once the user lets go this event ends and a final call to touchend is made before events all stop, but the div continues to momentum scroll.
This is the behaviour I want, but I also want to update the page during this momentum scrolling.
I trigger a call to requestAnimationFrame when the touchend event happens, and I can loop this while the momentum scroll occurs. But when I get DOM information, it's frozen until after the mometnum scroll ends.
I've tried using both the scroll position of the scrolling element and elementFromPoint, but both just have the position the scrolled div was in at the time touchend was triggered, and don't update until the momentum scroll ends.
Does anyone know of any way to get real time DOM information on iOS (6+, not worried about 5)
Here's some code I'm using:
var glideStart;
var bird_scanner = document.getElementById('bird-scanner');
bird_scanner.addEventListener('touchend',function()
{
glideStart = null;
requestAnimationFrame(glide);
});
function glide(timestamp)
{
// if we need to reset the timestamp
if( glideStart === null )
{
glideStart = timestamp;
}
// determine if we've moved
var bird_scanner = document.getElementById('bird-scanner');
console.log( document.elementFromPoint(337,568) );
// calculate progress (keep running for a very long time so we see what happens when momentum ends)
var progress = timestamp - glideStart;
if( progress < 10000 )
{
requestAnimationFrame(App.Controller.bird.glide);
}
}
Update
After a lot of attempts at this, I think it really is impossible without using some library to try and mimic the momentum scroll instead of using the built in option (something I find never really gives as smooth results). Apple are clearly very worried about things interfering with their momentum scroll animation and preventing it rendering properly.
I ended up removing the momentum scroll and just detecting swipes and moving through a bunch of elements at once when that's triggered.
I did notice some particularly strange behaviour. When I had webkit-overflow-scrolling: touch set on an element that was scrolling the page up/down and added a setTimeout(some_func,0) to the touchend event, the function wasn't triggered until the momentum scroll ended. When I tried the same thing on a scroll going left/right it triggered the function straight away. No clue why this happens, decided it must just be some strange webkit quirk.

Is there a way to set the window's scroll position without using scroll() or scrollTo()?

...the reason I ask is that Safari has a bug in its implementation of scroll() that is breaking my UI.
Imagine a page:
<body>
<div id="huge" style="width: 4000px; height: 4000px;"></div>
</body>
...so that you get both horizontal and vertical scrollbars. Now, normally when you press the scrollbar, the page scrolls (vertically). For the purposes of our fancy UI we don't want that to happen, so we squash the keyDown event:
window.onkeydown = function(e) {
if(e.keyCode == 32)
{
return false;
}
};
This works great...unless we decide that instead of preventing scrolling altogether, we want our own, custom scrolling behavior:
window.onkeydown = function(e) {
if(e.keyCode == 32)
{
window.scroll(foo, bar); // Causes odd behavior in Safari
return false;
}
};
In other browsers (Chrome, Firefox), this will instantaneously move the window's scroll position to the desired coordinates. But in Safari this causes the window to animate to the desired scroll position, similar to the scrolling animation that takes place if you press the space bar.
Note that if you trigger this scroll off of any key OTHER than the space bar, the animation does not take place; the window scrolls instantly as in other browsers.
If you happen to be scrolling, say, 1000 pixels or more, then the animated scroll can induce some serious discomfort.
I'm scratching my head trying to find a way around this. I suspect that there isn't one, but I'm hoping some God of Javascript here can suggest something. I'd really like to be able to use the space bar for this command.
If you know where in the document you want to scroll to then you can simply use named anchors. Setting document.location to the anchor (e.g. #top, #div50 or whatever) should be very reliable.
Use document.documentElement.scrollTop = ... (and document.body in some browsers).

Categories

Resources