Horizontal scrolling of a div using mouse and touch - javascript

Let's say I have a white-space: nowrap; div with overflow: hidden;. Its content is, of course, much longer than the div is, and needs to be scrolled to get revealed.
I was using this library, but it does not work for mobile devices with touch input. Do you know any alternative or ways to implement this feature?

Finally, my wish is fullfilled. Here I modified dragscroll.js library to enable touch support.
/* Modified dragscroll.js by Undust4able */
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(['exports'], factory);
} else if (typeof exports !== 'undefined') {
factory(exports);
} else {
factory((root.dragscroll = {}));
}
}(this, function (exports) {
var _window = window;
var _document = document;
var mousemove = 'mousemove';
var mouseup = 'mouseup';
var mousedown = 'mousedown';
var touchmove = 'touchmove';
var touchup = 'touchend';
var touchdown = 'touchstart';
var EventListener = 'EventListener';
var addEventListener = 'add'+EventListener;
var removeEventListener = 'remove'+EventListener;
var dragged = [];
var reset = function(i, el) {
for (i = 0; i < dragged.length;) {
el = dragged[i++];
el = el.container || el;
el[removeEventListener](mousedown, el.md, 0);
_window[removeEventListener](mouseup, el.mu, 0);
_window[removeEventListener](mousemove, el.mm, 0);
el[removeEventListener](touchdown, el.td, 0);
_window[removeEventListener](touchup, el.tu, 0);
_window[removeEventListener](touchmove, el.tm, 0);
}
// cloning into array since HTMLCollection is updated dynamically
dragged = [].slice.call(_document.getElementsByClassName('dragscroll'));
for (i = 0; i < dragged.length;) {
(function(el, lastClientX, lastClientY, pushed, scroller, cont){
(cont = el.container || el)[addEventListener](
mousedown,
cont.md = function(e) {
if (!el.hasAttribute('nochilddrag') ||
_document.elementFromPoint(
e.pageX, e.pageY
) == cont
) {
pushed = 1;
lastClientX = e.clientX;
lastClientY = e.clientY;
e.preventDefault();
}
}, 0
);
(cont = el.container || el)[addEventListener](
touchdown,
cont.td = function(e) {
if (!el.hasAttribute('nochilddrag') ||
_document.elementFromPoint(
e.pageX, e.pageY
) == cont
) {
pushed = 1;
e.preventDefault();
e = e.targetTouches[0];
lastClientX = e.clientX;
lastClientY = e.clientY;
}
}, 0
);
_window[addEventListener](
mouseup, cont.mu = function() {pushed = 0;}, 0
);
_window[addEventListener](
touchup, cont.tu = function() {pushed = 0;}, 0
);
_window[addEventListener](
mousemove,
cont.mm = function(e) {
if (pushed) {
(scroller = el.scroller||el).scrollLeft -=
(- lastClientX + (lastClientX=e.clientX));
scroller.scrollTop -=
(- lastClientY + (lastClientY=e.clientY));
}
}, 0
);
_window[addEventListener](
touchmove,
cont.tm = function(e) {
if (pushed) {
e = e.targetTouches[0];
(scroller = el.scroller||el).scrollLeft -=
(- lastClientX + (lastClientX=e.clientX));
scroller.scrollTop -=
(- lastClientY + (lastClientY=e.clientY));
}
}, 0
);
})(dragged[i++]);
}
}
if (_document.readyState == 'complete') {
reset();
} else {
_window[addEventListener]('load', reset, 0);
}
exports.reset = reset;
}));

Make a container div with overflow-y: hidden;overflow-x: scroll; and set it to whatever pre-determined height you want.
Then have your inner div that will house the content set to position:absolute; and set its width to whatever size you need the accommodate your content.
The content will scroll with the mouse and by touch.
Sounds kinda like you're going for a netflix style side scroller - check out this codepen I've done up that shows what I was just talking about.
http://codepen.io/hoonin_hooligan/pen/aZBxRG

Related

Customised scroll isnt working on smartphones

i have an issue concerning a JS scrolling function.
const scroll = document.querySelectorAll(".scroll");
const maxIndex = 3; //NB DE PAGES
let index = 0;
let animationEnd = true;
let boolUp = 0;
const start = {
x: 0,
y: 0
};
function touchStart(event) {
event.preventDefault();
start.x = event.touches[0].pageX;
start.y = event.touches[0].pageY;
}
function touchMove(event) {
event.preventDefault();
const offset = {};
offset.x = start.x - event.touches[0].pageX;
offset.y = start.y - event.touches[0].pageY;
scrollHandler({
deltaY: offset.y
});
}
function scrollHandler(e) {
if(e.preventDefault) e.preventDefault();
if (animationEnd) {
if (e.deltaY > 0) index++;
else index--;
if (index < 0) index = 0;
if (index > scroll.length - 1) index = scroll.length - 1;
scroll[0].style.marginTop = "-" + index * 100 + "vh";
animationEnd = false;
setTimeout(() => animationEnd = true, 450)
}
}
function keyScroll(e) {
if (e.key == "ArrowUp") {
index--;
if (index < 0) {
index = 0;
}
scroll[0].style.marginTop = "-" + index * 100 + "vh";
animationEnd = false;
setTimeout(() => animationEnd = true, 450);
} else if (e.key == "ArrowDown") {
if (index < maxIndex) {
index++;
scroll[0].style.marginTop = "-" + index * 100 + "vh";
animationEnd = false;
setTimeout(() => animationEnd = true, 450);
}
}
}
I'm calling those by body event listeners :
document.addEventListener("scroll", (e) => e.preventDefault())
document.body.addEventListener("keydown", keyScroll);
document.body.addEventListener("wheel", scrollHandler,);
document.body.addEventListener("touchstart", touchStart, false);
document.body.addEventListener("touchmove", touchMove, false);
It's working perfectly => example at https://darleanow.github.io .
But when i'm on smartphone (Iphone), scroll might bug and the height of divs would appear different, you can try it on your own smartphone to see what i'm talking about, try scrolling a bit fast etc...
If anybody has an idea :)
This isn't a solution necessarily, but you might try printing scroll[0].stlye.marginTop to the console every time it changes.
If that value is never erroneous, I'd guess the issue is with the animation (maybe scrolling while it's animating, or something like that).

Using fixPageXY(e) and onmousemove() and the image wont move?

Is there something im missing here? I just want to select the image by clicking on it, it should drag with the mouse(no mouse key held down) until its clicked onto I different part of the screen. Ive used function fixPageXY(e) with a onmousemove function, followed a tutorial and still nothing.
<script type="text/javascript">
function fixPageXY(e) {
if (e.pageX == null && e.clientX != null ) {
var html = document.documentElement;
var body = document.body;
e.pageX = e.clientX + (html.scrollLeft || body && body.scrollLeft || 0);
e.pageX -= html.clientLeft || 0;
e.pageY = e.clientY + (html.scrollTop || body && body.scrollTop || 0);
e.pageY -= html.clientTop || 0;
}
}
}
document.getElementById('ball').onmousedown = function() {
this.style.position = 'absolute';
var self = this;
document.onmousemove = function(e) {
e = e || event;
fixPageXY(e);
// put ball center under mouse pointer. 25 is half of width/height
self.style.left = e.pageX-25+'px';
self.style.top = e.pageY-25+'px';
}
this.onmouseup = function() {
document.onmousemove = null;
}
}
</script>
My image is simply,
<body onload="onmousemove();onmouseup();">
<img id="ball" src="ball.png" style="width:100px;height:100px;"/>
</body>
Im using google chrome, could this be an issue? many thanks for your help in advance.
There were a few syntax errors within your code, which if you are running Chrome you can just hit F12 on your keyboard and it will bring up the console allowing you to read whatever errors may be there. Here's a fiddle with just a few tweaks made to your code that allows it to run smoothly... and by tweaks, I mean there was an extra closing bracket after defining the function and the functions you called in body onload cannot me accessed that way so I deleted that and it worked.
This code work fine :
function fixPageXY(e) {
if(e.pageX == null && e.clientX != null ) {
var html = document.documentElement, body = document.body;
e.pageX = e.clientX + (html.scrollLeft || body && body.scrollLeft || 0);
e.pageX -= html.clientLeft || 0;
e.pageY = e.clientY + (html.scrollTop || body && body.scrollTop || 0);
e.pageY -= html.clientTop || 0;
}
}
document.getElementById("ball2").onmousedown = function () {
this.style.position = "absolute";
var self = this;
document.onmousemove = function (e) {
e = e || event;
fixPageXY (e);
self.style.left = e.pageX-25+'px';
self.style.top = e.pageY-25+'px';
}
this.onmouseup = function () {
document.onmousemove = null;
}
}
document.getElementById("ball2").ondragstart = function () { return false; }

How to add a padding top to smooth scroll

I have implemented a javascript smooth scroll in a one page site and works perfectly. However, because I have a fixed nav at the top of the page, when the page scrolls to the anchor, the top of the page disappears behind the nav. How can I offset the scroll of 90px?
Here is the code:
var ss = {
fixAllLinks: function() {
// Get a list of all links in the page
var allLinks = document.getElementsByTagName('a');
// Walk through the list
for (var i=0;i<allLinks.length;i++) {
var lnk = allLinks[i];
if ((lnk.href && lnk.href.indexOf('#') != -1) &&
( (lnk.pathname == location.pathname) ||
('/'+lnk.pathname == location.pathname) ) &&
(lnk.search == location.search)) {
// If the link is internal to the page (begins in #)
// then attach the smoothScroll function as an onclick
// event handler
ss.addEvent(lnk,'click',ss.smoothScroll);
}
}
},
smoothScroll: function(e) {
// This is an event handler; get the clicked on element,
// in a cross-browser fashion
if (window.event) {
target = window.event.srcElement;
} else if (e) {
target = e.target;
} else return;
// Make sure that the target is an element, not a text node
// within an element
if (target.nodeName.toLowerCase() != 'a') {
target = target.parentNode;
}
// Paranoia; check this is an A tag
if (target.nodeName.toLowerCase() != 'a') return;
// Find the <a name> tag corresponding to this href
// First strip off the hash (first character)
anchor = target.hash.substr(1);
// Now loop all A tags until we find one with that name
var allLinks = document.getElementsByTagName('a');
var destinationLink = null;
for (var i=0;i<allLinks.length;i++) {
var lnk = allLinks[i];
if (lnk.name && (lnk.name == anchor)) {
destinationLink = lnk;
break;
}
}
if (!destinationLink) destinationLink = document.getElementById(anchor);
// If we didn't find a destination, give up and let the browser do
// its thing
if (!destinationLink) return true;
// Find the destination's position
var destx = destinationLink.offsetLeft;
var desty = destinationLink.offsetTop;
var thisNode = destinationLink;
while (thisNode.offsetParent &&
(thisNode.offsetParent != document.body)) {
thisNode = thisNode.offsetParent;
destx += thisNode.offsetLeft;
desty += thisNode.offsetTop;
}
// Stop any current scrolling
clearInterval(ss.INTERVAL);
cypos = ss.getCurrentYPos();
ss_stepsize = parseInt((desty-cypos)/ss.STEPS);
ss.INTERVAL =
setInterval('ss.scrollWindow('+ss_stepsize+','+desty+',"'+anchor+'")',20);
// And stop the actual click happening
if (window.event) {
window.event.cancelBubble = true;
window.event.returnValue = false;
}
if (e && e.preventDefault && e.stopPropagation) {
e.preventDefault();
e.stopPropagation();
}
},
scrollWindow: function(scramount,dest,anchor) {
wascypos = ss.getCurrentYPos();
isAbove = (wascypos < dest);
window.scrollTo(0,wascypos + scramount);
iscypos = ss.getCurrentYPos();
isAboveNow = (iscypos < dest);
if ((isAbove != isAboveNow) || (wascypos == iscypos)) {
// if we've just scrolled past the destination, or
// we haven't moved from the last scroll (i.e., we're at the
// bottom of the page) then scroll exactly to the link
window.scrollTo(0,dest);
// cancel the repeating timer
clearInterval(ss.INTERVAL);
// and jump to the link directly so the URL's right
location.hash = anchor;
}
},
getCurrentYPos: function() {
if (document.body && document.body.scrollTop)
return document.body.scrollTop;
if (document.documentElement && document.documentElement.scrollTop)
return document.documentElement.scrollTop;
if (window.pageYOffset)
return window.pageYOffset;
return 0;
},
addEvent: function(elm, evType, fn, useCapture) {
// addEvent and removeEvent
// cross-browser event handling for IE5+, NS6 and Mozilla
// By Scott Andrew
if (elm.addEventListener){
elm.addEventListener(evType, fn, useCapture);
return true;
} else if (elm.attachEvent){
var r = elm.attachEvent("on"+evType, fn);
return r;
} else {
alert("Handler could not be removed");
}
}
}
ss.STEPS = 25;
ss.addEvent(window,"load",ss.fixAllLinks);
Thanks in advance for your help!
You can do a calculation when setting the destination coordinates:
// Find the destination's position
var destx = destinationLink.offsetLeft;
var desty = destinationLink.offsetTop;
var thisNode = destinationLink;
while (thisNode.offsetParent &&
(thisNode.offsetParent != document.body)) {
thisNode = thisNode.offsetParent;
destx += thisNode.offsetLeft;
desty += thisNode.offsetTop;
}
//subtract nav from offset position
desty = desty - 90;
if(desty < 0){ desty = 0; }
That being said, using a static number is dangerous business. Might make more sense to calculate minus the header's actual height instead.
Simply make changes in the CSS:
html{
scroll-behavior: smooth;
scroll-padding-top: 50px;
}
This will handle your fixed header issue.

Parallax Background Positioning Scrolling

I have just developed a new parallax scrolling script. I have it working just the way I want however there is just 1 issue with it currently.
I want the script to start scrolling the background image at the y coord that is specified in the css stylesheet by default. Instead my script seems to be resetting the CSS y coord to 0 before scrolling the image. This is obviously undesired behavior.
// Parallax scripting starts here
$.prototype.jpayParallax = function(userOptions){
var _api = {};
_api.utils = {};
_api.utils.isElementInViewport = function(el){
if (typeof jQuery === "function" && el instanceof jQuery) {
el = el[0];
}
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
);
}
_api.utils.debounceScrollWheel = (function(){
$(function(){
var $window = $(window); //Window object
var scrollTime = 0.3; //Scroll time
var scrollDistance = 50; //Distance. Use smaller value for shorter scroll and greater value for longer scroll
$window.on("mousewheel DOMMouseScroll", function(event){
event.preventDefault();
var delta = event.originalEvent.wheelDelta/120 || -event.originalEvent.detail/3;
var scrollTop = $window.scrollTop();
var finalScroll = scrollTop - parseInt(delta*scrollDistance);
TweenMax.to($window, scrollTime, {
scrollTo : { y: finalScroll, autoKill:true },
ease: Power1.easeOut, //For more easing functions see http://api.greensock.com/js/com/greensock/easing/package-detail.html
autoKill: true,
overwrite: 5
});
});
});
})();
_api.selector = 'data-jpay-parallax';
_api.methods = {};
_api.methods.checkForVisibleParallaxEls = function(){
$('['+_api.selector+']').each(function(){
var instanceObject = $(this);
var origBgPos = $(this).css('backgroundPosition').split(' ');
var options = $(this).data('jpay-parallax');
console.log(origBgPos)
if (_api.utils.isElementInViewport(instanceObject)){
_api.methods.doParallax(instanceObject, options);
}
});
}
_api.methods.doParallax = function(instanceToManip, userOptions){
var direction = userOptions.settings.direction;
var orientation = userOptions.settings.orientation;
var speed = userOptions.settings.speed;
var type = userOptions.settings.type;
var speedInt;
var getSpeed = (function(){
if (speed){
switch(speed){
case 'slow':
speedInt = 10;
break;
case 'fast':
speedInt = 5;
break;
case 'faster':
speedInt = 1;
break;
default:
throw new TypeError('Unknown speed parameter added to module instructions');
}
}
})();
var distToTopInt = function(){
if (typeof speedInt === 'number'){
return $(window).scrollTop()/speedInt;
}
else {
return $(window).scrollTop();
}
}
var origPos = instanceToManip.css('backgroundPosition').split(' ');
var origPosX = parseInt(origPos[0]);
var origPosY = parseInt(origPos[1]);
var newPosY = origPosY += distToTopInt();
var newPosX = origPosX += distToTopInt();
if (orientation === 'vertical' && direction !== 'reverse'){
instanceToManip.css('backgroundPositionY', newPosX+'px');
}
else if (orientation === 'vertical' && direction === 'reverse'){
instanceToManip.css('backgroundPositionY', -newPosX+'px');
}
else if (orientation == 'horizontal' && direction !== 'reverse'){
instanceToManip.css('backgroundPositionX', newPosX+'px');
}
else if (orientation == 'horizontal' && direction === 'reverse'){
instanceToManip.css('backgroundPositionX', -newPosY+'px');
}
}
$(window).on('scroll', _api.methods.checkForVisibleParallaxEls)
};
$.fn.jpayParallax();
Here is the pen:
http://codepen.io/nicholasabrams/pen/OPxKXm/?editors=001
BONUS: Why does this script also mess with the css set backgroundSize property when the script never accesses it?
I am looking for advice in where in the script to cache the original CSS background image y coord value so that it becomes incremented from there instead of starting at 0px /0 for each instance. Thanks again for the help!

Swipe Events in Mobile Safari Intermittently Breaking

I'm trying to set up swipe events for a site I'm working on. Basically, when someone swipes the content container, child div elements of that will change content depending on the page one is on. The actual div "contentwrapper" that I am attaching the swipe listeners to does not change.
To do some animations, I have a previous and next page container that stores content. I removed the ajax function where I populate these for simplicity.
This works when going forwards but when going backwards, I seem to lose the preventDefault behavior and the whole page moves with my finger swipe. This problem only happens intermittently and aways when going backwards.
// Slightly modified code by Dave Dunkin
// http://rabblerule.blogspot.com/2009/08/detecting-swipe-in-webkit.html
function addSwipeListener(el, listener)
{
var startX;
var dx;
var direction;
function cancelTouch()
{
el.removeEventListener('touchmove', onTouchMove);
el.removeEventListener('touchend', onTouchEnd);
startX = null;
startY = null;
direction = null;
}
function onTouchMove(e)
{
if (e.touches.length > 1)
{
cancelTouch();
}
else
{
dx = e.touches[0].pageX - startX;
var dy = e.touches[0].pageY - startY;
if (direction == null)
{
direction = dx;
}
else if ((direction < 0 && dx > 0) || (direction > 0 && dx < 0) || Math.abs(dy) > 400)
{
cancelTouch();
}
}
}
function onTouchEnd(e)
{
cancelTouch();
if (Math.abs(dx) > 30)
{
listener({ target: el, direction: dx > 0 ? 'right' : 'left' });
dx = 0;
}
}
function onTouchStart(e)
{
e.preventDefault();
e.stopPropagation();
if (e.touches.length == 1)
{
startX = e.touches[0].pageX;
startY = e.touches[0].pageY;
el.addEventListener('touchmove', onTouchMove, false);
el.addEventListener('touchend', onTouchEnd, false);
}
}
el.addEventListener('touchstart', onTouchStart, false);
}
Add Swipe Listener
addSwipeListener(document.getElementById("contentwrapper"), function(e) {
swipePageChange(e);
});
function swipePageChange(e) {
if(e.direction == "left") {
moveforward();
}
if(e.direction == "right") {
movebackward();
}
}
Page Movement Events
function moveforward() {
$("#previouspagecontainer").css("z-index","20");
$("#newpagecontainer").css("z-index","40");
$("#previouspage").html($("#circular").html())
$("#newpagecontainer")[0].style.webkitAnimationName = 'flippageright';
$("#newpagecontainer")[0].addEventListener('webkitAnimationEnd', function() {
$("#currentpagecontainer").css("z-index","30");
$("#newpagecontainer")[0].style.webkitAnimationName = '';
$("#circular").html($("#nextpage").html());
});
return false;
}
function movebackward() {
$("#previouspagecontainer").css("z-index","40");
$("#currentpagecontainer").css("z-index","30");
$("#newpagecontainer").css("z-index","20");
$("#previouspagecontainer")[0].style.webkitAnimationName = 'flippageleft';
$("#previouspagecontainer")[0].addEventListener('webkitAnimationEnd', function() {
$("#previouspagecontainer")[0].style.webkitAnimationName = '';
$("#circular").html($("#previouspage").html());
});
return false;
}
The problem was caused by an unrelated element being removed from the DOM. I'm not quite sure why this resulted in breaking the swipe events but stopping this practice fixed my issue.

Categories

Resources