Slider slides many times - javascript

I am trying to create a slider with event listeners touchstart and touchmove.
The slider works very good, if you click on the buttons. But if you move your finger from left to right, it slides many times until the last image but it should only slide once. Also you cannot slide back.
var i = 0;
// Go next
$('.next').bind('click', function() {
niceSlider('left', '<');
});
// Go Back
$('.back').bind('click', function() {
niceSlider('right', '>', 0);
});
// Greather or less
function greatherOrLess(num1, operator, num2) {
if (operator == '<') {
return (num1 < num2) ? true : false;
}
else if (operator == '>') {
return (num1 > num2) ? true : false;
}
}
// Slider
function niceSlider(direction, operator, NumberOfAllImages = 4, position = 600) {
var direction = (direction == 'left') ? '-' : '+';
if (greatherOrLess(i, operator, NumberOfAllImages)) {
if (direction == '+' || direction == '-') {
$('li').animate({'left': direction + '=600px'}, 300).delay(600);
x = (direction == '-') ? i++ : i--;
}
}
console.log($('li:first').position().left);
console.log(x);
}
// Event Listener
var slider = document.querySelector('.slider');
slider.addEventListener('touchstart', handleTouchStart, false);
slider.addEventListener('touchmove', handleTouchMove, false);
// Start from touch
function handleTouchStart(evt) {
startClientX = evt.touches[0].clientX;
startClientY = evt.touches[0].clientY;
}
// Move from touch
function handleTouchMove(evt) {
moveClientX = evt.touches[0].clientX;
moveClientY = evt.touches[0].clientY;
var diffClientX = startClientX - moveClientX;
var diffClientY = startClientY - moveClientY;
if (Math.abs(diffClientX) > Math.abs(diffClientY)) {
if (diffClientX > 0) {
niceSlider('left', '<');
}
else {
niceSlider('right', '>');
}
}
}
There must be something wrong with the function handleTouchMove. How can I fix it?
https://jsfiddle.net/6t1wx95f/16/

function handleTouchStart(evt) {
startClientX = evt.touches[0].clientX;
startClientY = evt.touches[0].clientY;
checkTouch = true;
}
// Move from touch
function handleTouchMove(evt) {
moveClientX = evt.touches[0].clientX;
moveClientY = evt.touches[0].clientY;
if (checkTouch) {
var diffClientX = startClientX - moveClientX;
var diffClientY = startClientY - moveClientY;
if (Math.abs(diffClientX) > Math.abs(diffClientY)) {
if (diffClientX > 0) {
niceSlider('left', '<');
} else {
niceSlider('right', '>', 0);
}
}
checkTouch = false;
}
}
function handleTouchEnd(evt) {
checkTouch = true;
}
Here is jsFiddle, check it for only once use a boolean value. On touch move next function was calling on every move.

Related

Character will not jump after touching in JS

I am programming collision detection in JS for a platformer. For some reason, when my character touches the ground on the top, it won't jump again. Here's my code:
if (isCollideY(platforms[i].getBoundingClientRect(), document.getElementById('spriteNotReal').getBoundingClientRect()) == true) {
if (falling == true && (jumping == false)) {
moveY = platforms[i].getBoundingClientRect().y + 3;
momentumY = 0;
onSolidGround = true;
}
}
if (event.code == 'KeyW' && (moveY <= 300)) {
moveY += 1;
move (moveX, moveY);
momentumY = momentumY + 20;
onSolidGround = false;
falling = false;
jumping = true;
}
else if (onSolidGround == false) {
if (momentumY < 0) {
falling = true;
}
else if (momentumY > 0) {
jumping = true;
}
else {
jumping = false;
}
moveX += momentumX / 3 + 1;
document.getElementById("spriteNotReal").src = "jumpmain.gif";
}
My problem was somewhat stupid. After checking the input code, I realized that the jump wasn't happening because it would only jump while on the "platform" I set up to test, not while it was actually on a platform. Here's the improved code:
if (event.code == 'KeyW' && (onSolidGround == true)) {
moveY += 1;
move (moveX, moveY);
momentumY = momentumY + 20;
onSolidGround = false;
falling = false;
jumping = true;
}

How To add automatic scrolling in slider

I want to add automatic scrolling time to my slider code but unable to do it can you please suggest me something to help me out with the code to make this slider slide automatic with a set interval of time.
'use strict';
$(document).ready(function () {
var $slides = $('.con__slide').length,
topAnimSpd = 650,
textAnimSpd = 1000,
nextSlideSpd = topAnimSpd + textAnimSpd,
animating = true,
animTime = 4000,
curSlide = 1,
nextSlide,
scrolledUp;
setTimeout(function () {
animating = false;
}, 2300);
//navigation up function
function navigateUp() {
if (curSlide > 1) {
scrolledUp = true;
pagination(curSlide);
curSlide--;
}
}
//navigation down function
function navigateDown() {
if (curSlide < $slides) {
scrolledUp = false;
pagination(curSlide);
curSlide++;
console.log(curSlide);
}
}
$(window).on('load', function () {
$('.con__slide--1').addClass('active');
});
//pagination function
function pagination(slide, target) {
animating = true;
// Check if pagination was triggered by scroll/keys/arrows or direct click. If scroll/keys/arrows then check if scrolling was up or down.
if (target === undefined) {
nextSlide = scrolledUp ? slide - 1 : slide + 1;
} else {
nextSlide = target;
}
////////// Slides //////////
$('.con__slide--' + slide).removeClass('active');
setTimeout(function () {
$('.con__slide--' + nextSlide).addClass('active');
}, nextSlideSpd);
////////// Nav //////////
$('.con__nav-item--' + slide).removeClass('nav-active');
$('.con__nav-item--' + nextSlide).addClass('nav-active');
setTimeout(function () {
animating = false;
}, animTime);
}
// Mouse wheel trigger
$(document).on('mousewheel DOMMouseScroll', function (e) {
var delta = e.originalEvent.wheelDelta;
if (animating) return;
// Mouse Up
if (delta > 0 || e.originalEvent.detail < 0) {
navigateUp();
} else {
navigateDown();
}
});
// Direct trigger
$(document).on("click", ".con__nav-item:not(.nav-active)", function () {
// Essential to convert target to a number with +, so curSlide would be a number
var target = +$(this).attr('data-target');
if (animating) return;
pagination(curSlide, target);
curSlide = target;
});
// Arrow trigger
$(document).on('click', '.con__nav-scroll', function () {
var target = $(this).attr('data-target');
if (animating) return;
if (target === 'up') {
navigateUp();
} else {
navigateDown();
}
});
// Key trigger
$(document).on("keydown", function (e) {
if (animating) return;
if (e.which === 38) {
navigateUp();
} else if (e.which === 40) {
navigateDown();
}
});
var topLink = $(".con__slide--4-top-h-link"),
botLink = $(".con__slide--4-bot-h-link");
$(".con__slide--4-top-h-link, .con__slide--4-bot-h-link").on({
mouseenter: function mouseenter() {
topLink.css('text-decoration', 'underline');
botLink.css('text-decoration', 'underline');
},
mouseleave: function mouseleave() {
topLink.css('text-decoration', 'none');
botLink.css('text-decoration', 'none');
}
});
});
Hope you understand the above code if you have any query in it feel free to ask me and please help me out as soon as possible.
Added setInterval in your code.
setInterval(() => {
if (curSlide >= $slides){
if (animating) return;
pagination(4, 1);
curSlide = 1;
}
else
navigateDown();
}, 10000);
Check updated fiddle.
update below navigateDown code.
//navigation down function
function navigateDown() {
if (curSlide < $slides) {
scrolledUp = false;
pagination(curSlide);
curSlide++;
console.log(curSlide);
}else{
curSlide=1;
pagination(4,1)
}
}
Add this below line
setInterval(navigateDown,7000);

Horizontal scrolling of a div using mouse and touch

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

JS : Event on ScrollDown and ScrollUp

I currently have a animated sprite that walks when you press the left and right keys on the keyboard. What I would like to do is to make the sprite walk-right when you scroll down and walk left when you scroll up. I would also like to make the sprite stop walking when the user stops scrolling. Thanks in advance!
I tried using the $(window).scroll function with variables of current and lastscroll positions, but it didn't work.
function walk(e) {
var keyCode = e.keyCode;
if (keyCode === 39) {
key.right = true;
} else if (keyCode === 37) {
key.left = true;
}
if (key.right === true) {
trans += 0;
translate();
sprite.classList.remove('left');
sprite.classList.add('right');
sprite.classList.add('walk-right');
} else if (key.left === true) {
trans -= 0;
translate();
sprite.classList.remove('right');
sprite.classList.add('left');
sprite.classList.add('walk-left');
}
}
function stop(e) {
var keyCode = e.keyCode;
if (keyCode === 39) {
key.right = false;
} else if (keyCode === 37) {
key.left = false;
}
if (key.right === false) {
sprite.classList.remove('walk-right');
} if (key.left === false) {
sprite.classList.remove('walk-left');
}
}
Update:
Here's a better version; I merged the keyboard and scroll code into the same event for you:
if (document.addEventListener) {
// IE9, Chrome, Safari, Opera
document.addEventListener("mousewheel", walk, false);
// Firefox
document.addEventListener("DOMMouseScroll", walk, false);
}else{
// IE 6/7/8
document.attachEvent("onmousewheel", walk);
}
function walk(e) {
var e = window.event || e; // old IE support
if (e.keyCode) {
//keyboard input
if (e.keyCode === 39) {
key.right = true;
} else if (keyCode === 37) {
key.left = true;
}
}else{
//scroll input
var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
if (delta == 1) {
//walk right
key.right = true;
key.left = false;
}else if (delta == -1) {
//walk left
key.left = true;
key.right = false;
}else{
//stop
key.left = false;
key.right = false;
sprite.classList.remove('walk-right');
sprite.classList.remove('walk-left');
}
}
if (key.right === true) {
trans += 0;
translate();
sprite.classList.remove('left');
sprite.classList.add('right');
sprite.classList.add('walk-right');
} else if (key.left === true) {
trans -= 0;
translate();
sprite.classList.remove('right');
sprite.classList.add('left');
sprite.classList.add('walk-left');
}
}
Previous answer:
Here you go:
if (document.addEventListener) {
// IE9, Chrome, Safari, Opera
document.addEventListener("mousewheel", scroll, false);
// Firefox
document.addEventListener("DOMMouseScroll", scroll, false);
}else{
// IE 6/7/8
document.attachEvent("onmousewheel", scroll);
}
function scroll(e) {
var e = window.event || e; // old IE support
var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
if (delta == 1) {
//walk right
key.right = true;
key.left = false;
}else if (delta == -1) {
//walk left
key.left = true;
key.right = false;
}else{
//stop
key.left = false;
key.right = false;
sprite.classList.remove('walk-right');
sprite.classList.remove('walk-left');
}
if (key.right === true) {
trans += 0;
translate();
sprite.classList.remove('left');
sprite.classList.add('right');
sprite.classList.add('walk-right');
} else if (key.left === true) {
trans -= 0;
translate();
sprite.classList.remove('right');
sprite.classList.add('left');
sprite.classList.add('walk-left');
}
}
Use document.addEventListener instead:
var currentY = 0;
document.addEventListener('scroll', function(e){
// some logic
key.right = false;
key.left = false;
currentY < window.pageYOffset ? key.right = true : key.left = true;
currentY = window.pageYOffset;
})

Easy Smooth Scroll Plugin: How do I offset scroll?

I am using the Easy Smooth Scroll Plugin for Wordpress.
Below is the .js file that the plugin uses:
var ss = {
fixAllLinks: function() {
var allLinks = document.getElementsByTagName('a');
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)) {
ss.addEvent(lnk, 'click', ss.smoothScroll);
}
}
},
smoothScroll: function(e) {
if (window.event) {
target = window.event.srcElement;
} else if (e) {
target = e.target;
} else return;
if (target.nodeName.toLowerCase() != 'a') {
target = target.parentNode;
}
if (target.nodeName.toLowerCase() != 'a') return;
anchor = target.hash.substr(1);
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 (!destinationLink) return true;
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;
}
clearInterval(ss.INTERVAL);
cypos = ss.getCurrentYPos();
ss_stepsize = parseInt((desty - cypos) / ss.STEPS);
ss.INTERVAL = setInterval('ss.scrollWindow(' + ss_stepsize + ',' + desty + ',"' + anchor + '")', 10);
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)) {
window.scrollTo(0, dest);
clearInterval(ss.INTERVAL);
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) {
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);
The live page is here: http://iamjoepro.com/album/promaha/
I have the smooth scroll scrolling to an anchor, but I would like to offset it by the height of my fixed header (120px)
I am no javascript expert, I'm hoping this is easy for someone, but I can't decipher where to add the offset in my .js file?
I had a similar issue and found that the following solution worked for me.
Change the line:
var desty = destinationLink.offsetTop;
to read:
var desty = destinationLink.offsetTop - 120;
(where '120' is the height in pixels of your fixed header)
Then, remove the line:
location.hash = anchor;
(otherwise, the page will scroll to your 120px offset but then return back to the location of the anchor)
Hope this helps!

Categories

Resources