Tree.js ';' expected. ts(1005) - javascript

I'm working on putting together a tutorial that I'm following on three.js and Vanilla.js I have this problem with the first line onscroll(){ is expected a ';', but doesn't make any sense to me. It seems that there is a problem with Typescript or something. I really appreciate your help.
onscroll(){
window.addEventListener("wheel", (e) => {
if (e.deltaY > 0) {
this.lerp.target += 0.01;
this.back = true;
} else {
this.lerp.target -= 0.01;
this.back = false;
}
});
}

You're missing function in front of onscroll()
function onscroll() {
window.addEventListener("wheel", (e) => {
if (e.deltaY > 0) {
this.lerp.target += 0.01;
this.back = true;
} else {
this.lerp.target -= 0.01;
this.back = false;
}
});
}
If you want to define a function without function key, you can use an arrow function
const onscroll = () => {
window.addEventListener("wheel", (e) => {
if (e.deltaY > 0) {
this.lerp.target += 0.01;
this.back = true;
} else {
this.lerp.target -= 0.01;
this.back = false;
}
});
};

Related

how to make javascript game touch friendly?

I created flappy bird by following a youtube tutorial. Inside Bird.js there is a function called handleJump, inside that function when i put "Space", the bird jumps whenever i press space key on keyboard, but when i change it to "touchstart" the bird doesn't jump when i touch the screen! what am i doing wrong? what should i do?
The main page ( f.js ):
import { updateBird, setupBird, getBirdRect } from "./Bird.js";
import {
updatePipes,
setupPipes,
getPassedPipesCount,
getPipesRects,
} from "./Pipe.js";
//document.addEventListener("keypress", handleStart, { once: true });
document.addEventListener("touchstart", handleStart, { once: true });
const title = document.querySelector("[data-title]");
const subtitle = document.querySelector("[data-subtitle]");
let lastTime;
function updateLoop(time) {
if (lastTime == null) {
lastTime = time;
window.requestAnimationFrame(updateLoop);
return;
}
const delta = time - lastTime;
updateBird(delta);
updatePipes(delta);
if (checkLose()) return handleLose();
lastTime = time;
window.requestAnimationFrame(updateLoop);
}
function checkLose() {
const birdRect = getBirdRect();
const insidePipe = getPipesRects().some((rect) =>
isCollision(birdRect, rect)
);
const outsideWorld = birdRect.top < 0 || birdRect.bottom > window.innerHeight;
return outsideWorld || insidePipe;
}
function isCollision(rect1, rect2) {
return (
rect1.left < rect2.right &&
rect1.top < rect2.bottom &&
rect1.right > rect2.left &&
rect1.bottom > rect2.top
);
}
function handleStart() {
title.classList.add("hide");
setupBird();
setupPipes();
lastTime = null;
window.requestAnimationFrame(updateLoop);
}
function handleLose() {
setTimeout(() => {
title.classList.remove("hide");
subtitle.classList.remove("hide");
subtitle.textContent = `${getPassedPipesCount()} Pipes`;
document.addEventListener("touchstart", handleStart, { once: true });
}, 100);
}
Bird.js :
const birdElem = document.querySelector("[data-bird");
const BIRD_SPEED = 0.5;
const JUMP_DURATION = 120;
let timeSinceLastJump = Number.POSITIVE_INFINITY;
export function setupBird() {
setTop(window.innerHeight / 2);
document.removeEventListener("touchstart", handleJump); //keydown
document.addEventListener("touchstart", handleJump); //keydown
}
export function updateBird(delta) {
if (timeSinceLastJump < JUMP_DURATION) {
setTop(getTop() - BIRD_SPEED * delta);
} else {
setTop(getTop() + BIRD_SPEED * delta);
}
timeSinceLastJump += delta;
}
export function getBirdRect() {
return birdElem.getBoundingClientRect();
}
function setTop(top) {
birdElem.style.setProperty("--bird-top", top);
}
function getTop() {
return parseFloat(getComputedStyle(birdElem).getPropertyValue("--bird-top"));
}
function handleJump(e) {
if (e.code !== "touchstart") return;
timeSinceLastJump = 0;
}
I fixed it by removing the return
Before:
function handleJump(e) {
if (e.code !== "touchstart") return;
timeSinceLastJump = 0;
}
After:
function handleJump(e) {
if (e.code !== "touchstart");
timeSinceLastJump = 0;
}

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);

Slider slides many times

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.

up/down arrow scroll not working

up/down arrow scroll not working in jquery scrolify plugin.I want to do the scroll with both page up/down button and in up/down arrow button click.
page up/down arrow working fine as I expect.up/down button click not scroll as page scroll
if(e.keyCode==33 ) { //working
if(index>0) {
if(atTop()) {
e.preventDefault();
index--;
//index, instant, callbacks
animateScroll(index,false,true);
}
}
} else if(e.keyCode==34) { //working
if(index<heights.length-1) {
if(atBottom()) {
e.preventDefault();
index++;
//index, instant, callbacks
animateScroll(index,false,true);
}
}
}
if(e.keyCode==38) { //not working
if(index>0) {
if(atTop()) {
e.preventDefault();
index--;
//index, instant, callbacks
animateScroll(index,false,true);
console.log('up arrow');
}
}
} else if(e.keyCode==40) { //not working
if(index<heights.length-1) {
if(atBottom()) {
e.preventDefault();
index++;
//index, instant, callbacks
animateScroll(index,false,true);
console.log('down arrow');
}
}
}
/*!
* jQuery Scrollify
* Version 1.0.5
*
* Requires:
* - jQuery 1.7 or higher
*
* https://github.com/lukehaas/Scrollify
*
* Copyright 2016, Luke Haas
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
If section being scrolled to is an interstitialSection and the last section on page
then value to scroll to is current position plus height of interstitialSection
*/
(function (global,factory) {
"use strict";
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], function($) {
return factory($, global, global.document);
});
} else if (typeof module === 'object' && module.exports) {
// Node/CommonJS
module.exports = function( root, jQuery ) {
if ( jQuery === undefined ) {
// require('jQuery') returns a factory that requires window to
// build a jQuery instance, we normalize how we use modules
// that require this pattern but the window provided is a noop
// if it's defined (how jquery works)
if ( typeof window !== 'undefined' ) {
jQuery = require('jquery');
} else {
jQuery = require('jquery')(root);
}
}
factory(jQuery, global, global.document);
return jQuery;
};
} else {
// Browser globals
factory(jQuery, global, global.document);
}
}(typeof window !== 'undefined' ? window : this, function ($, window, document, undefined) {
"use strict";
var heights = [],
names = [],
elements = [],
overflow = [],
index = 0,
currentIndex = 0,
interstitialIndex = 1,
hasLocation = false,
timeoutId,
timeoutId2,
$window = $(window),
top = $window.scrollTop(),
scrollable = false,
locked = false,
scrolled = false,
manualScroll,
swipeScroll,
util,
disabled = false,
scrollSamples = [],
scrollTime = new Date().getTime(),
firstLoad = true,
initialised = false,
wheelEvent = 'onwheel' in document ? 'wheel' : document.onmousewheel !== undefined ? 'mousewheel' : 'DOMMouseScroll',
settings = {
//section should be an identifier that is the same for each section
section: ".section",
//sectionName: "section-name",
interstitialSection: "",
easing: "easeOutExpo",
scrollSpeed: 500,
offset : 0,
scrollbars: true,
target:"html,body",
standardScrollElements: false,
setHeights: true,
overflowScroll:true,
before:function() {},
after:function() {},
afterResize:function() {},
afterRender:function() {}
};
function animateScroll(index,instant,callbacks) {
if(currentIndex===index) {
callbacks = false;
}
if(disabled===true) {
return true;
}
if(names[index]) {
scrollable = false;
if(callbacks) {
settings.before(index,elements);
}
interstitialIndex = 1;
if(settings.sectionName && !(firstLoad===true && index===0)) {
if(history.pushState) {
try {
history.replaceState(null, null, names[index]);
} catch (e) {
if(window.console) {
console.warn("Scrollify warning: This needs to be hosted on a server to manipulate the hash value.");
}
}
} else {
window.location.hash = names[index];
}
}
if(instant) {
$(settings.target).stop().scrollTop(heights[index]);
if(callbacks) {
settings.after(index,elements);
}
} else {
locked = true;
if( $().velocity ) {
$(settings.target).stop().velocity('scroll', {
duration: settings.scrollSpeed,
easing: settings.easing,
offset: heights[index],
mobileHA: false
});
} else {
$(settings.target).stop().animate({
scrollTop: heights[index]
}, settings.scrollSpeed,settings.easing);
}
if(window.location.hash.length && settings.sectionName && window.console) {
try {
if($(window.location.hash).length) {
console.warn("Scrollify warning: There are IDs on the page that match the hash value - this will cause the page to anchor.");
}
} catch (e) {
console.warn("Scrollify warning:", window.location.hash, "is not a valid jQuery expression.");
}
}
$(settings.target).promise().done(function(){
currentIndex = index;
locked = false;
firstLoad = false;
if(callbacks) {
settings.after(index,elements);
}
});
}
}
}
function isAccelerating(samples) {
function average(num) {
var sum = 0;
var lastElements = samples.slice(Math.max(samples.length - num, 1));
for(var i = 0; i < lastElements.length; i++){
sum += lastElements[i];
}
return Math.ceil(sum/num);
}
var avEnd = average(10);
var avMiddle = average(70);
if(avEnd >= avMiddle) {
return true;
} else {
return false;
}
}
$.scrollify = function(options) {
initialised = true;
$.easing['easeOutExpo'] = function(x, t, b, c, d) {
return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
};
manualScroll = {
/*handleMousedown:function() {
if(disabled===true) {
return true;
}
scrollable = false;
scrolled = false;
},*/
handleMouseup:function() {
if(disabled===true) {
return true;
}
scrollable = true;
if(scrolled) {
//instant,callbacks
manualScroll.calculateNearest(false,true);
}
},
handleScroll:function() {
if(disabled===true) {
return true;
}
if(timeoutId){
clearTimeout(timeoutId);
}
timeoutId = setTimeout(function(){
scrolled = f;
if(scrollable===false) {
return false;
}
scrollable = false;
//instant,callbacks
manualScroll.calculateNearest(false,false);
}, 200);
},
calculateNearest:function(instant,callbacks) {
top = $window.scrollTop();
var i =1,
max = heights.length,
closest = 0,
prev = Math.abs(heights[0] - top),
diff;
for(;i<max;i++) {
diff = Math.abs(heights[i] - top);
if(diff < prev) {
prev = diff;
closest = i;
}
}
if(atBottom() || atTop()) {
index = closest;
//index, instant, callbacks
animateScroll(closest,instant,callbacks);
}
},
/*wheel scroll*/
wheelHandler:function(e) {
if(disabled===true) {
return true;
} else if(settings.standardScrollElements) {
if($(e.target).is(settings.standardScrollElements) || $(e.target).closest(settings.standardScrollElements).length) {
return true;
}
}
if(!overflow[index]) {
e.preventDefault();
}
var currentScrollTime = new Date().getTime();
e = e || window.event;
var value = e.originalEvent.wheelDelta || -e.originalEvent.deltaY || -e.originalEvent.detail;
var delta = Math.max(-1, Math.min(1, value));
//delta = delta || -e.originalEvent.detail / 3 || e.originalEvent.wheelDelta / 120;
if(scrollSamples.length > 149){
scrollSamples.shift();
}
//scrollSamples.push(Math.abs(delta*10));
scrollSamples.push(Math.abs(value));
if((currentScrollTime-scrollTime) > 200){
scrollSamples = [];
}
scrollTime = currentScrollTime;
if(locked) {
return false;
}
if(delta<0) {
if(index<heights.length-1) {
if(atBottom()) {
if(isAccelerating(scrollSamples)) {
e.preventDefault();
index++;
locked = true;
//index, instant, callbacks
animateScroll(index,false,true);
} else {
return false;
}
}
}
} else if(delta>0) {
if(index>0) {
if(atTop()) {
if(isAccelerating(scrollSamples)) {
e.preventDefault();
index--;
locked = true;
//index, instant, callbacks
animateScroll(index,false,true);
} else {
return false
}
}
}
}
},
/*end of wheel*/
keyHandler:function(e) {
if(disabled===true) {
return true;
}
if(locked===true) {
return false;
}
if(e.keyCode==33 ) {
if(index>0) {
if(atTop()) {
e.preventDefault();
index--;
//index, instant, callbacks
animateScroll(index,false,true);
}
}
} else if(e.keyCode==34) {
if(index<heights.length-1) {
if(atBottom()) {
e.preventDefault();
index++;
//index, instant, callbacks
animateScroll(index,false,true);
}
}
}
if(e.keyCode==38) {
if(index>0) {
if(atTop()) {
e.preventDefault();
index--;
//index, instant, callbacks
animateScroll(index,false,true);
console.log('up arrow');
}
}
} else if(e.keyCode==40) {
if(index<heights.length-1) {
if(atBottom()) {
e.preventDefault();
index++;
//index, instant, callbacks
animateScroll(index,false,true);
console.log('down arrow');
}
}
}
/*home, end button testing*/
if(e.keyCode==35) {
for(index=6;index<1;index--)
{
console.log("worked on end button");
}
}
else if(e.keyCode==36) {
for(index=0;intex<1;index++)
{
console.log("worked on home button");
}
}
/*home,end button end*/
},
init:function() {
if(settings.scrollbars) {
$window.on('mousedown', manualScroll.handleMousedown);
$window.on('mouseup', manualScroll.handleMouseup);
$window.on('scroll', manualScroll.handleScroll);
} else {
$("body").css({"overflow":"hidden"});
}
$window.on(wheelEvent,manualScroll.wheelHandler);
$(document).bind(wheelEvent,manualScroll.wheelHandler);
$window.on('keydown', manualScroll.keyHandler);
}
};
swipeScroll = {
touches : {
"touchstart": {"y":-1,"x":-1},
"touchmove" : {"y":-1,"x":-1},
"touchend" : false,
"direction" : "undetermined"
},
options:{
"distance" : 30,
"timeGap" : 800,
"timeStamp" : new Date().getTime()
},
touchHandler: function(event) {
if(disabled===true) {
return true;
} else if(settings.standardScrollElements) {
if($(event.target).is(settings.standardScrollElements) || $(event.target).closest(settings.standardScrollElements).length) {
return true;
}
}
var touch;
if (typeof event !== 'undefined'){
if (typeof event.touches !== 'undefined') {
touch = event.touches[0];
switch (event.type) {
case 'touchstart':
swipeScroll.touches.touchstart.y = touch.pageY;
swipeScroll.touches.touchmove.y = -1;
swipeScroll.touches.touchstart.x = touch.pageX;
swipeScroll.touches.touchmove.x = -1;
swipeScroll.options.timeStamp = new Date().getTime();
swipeScroll.touches.touchend = false;
case 'touchmove':
swipeScroll.touches.touchmove.y = touch.pageY;
swipeScroll.touches.touchmove.x = touch.pageX;
if(swipeScroll.touches.touchstart.y!==swipeScroll.touches.touchmove.y && (Math.abs(swipeScroll.touches.touchstart.y-swipeScroll.touches.touchmove.y)>Math.abs(swipeScroll.touches.touchstart.x-swipeScroll.touches.touchmove.x))) {
//if(!overflow[index]) {
event.preventDefault();
//}
swipeScroll.touches.direction = "y";
if((swipeScroll.options.timeStamp+swipeScroll.options.timeGap)<(new Date().getTime()) && swipeScroll.touches.touchend == false) {
swipeScroll.touches.touchend = true;
if (swipeScroll.touches.touchstart.y > -1) {
if(Math.abs(swipeScroll.touches.touchmove.y-swipeScroll.touches.touchstart.y)>swipeScroll.options.distance) {
if(swipeScroll.touches.touchstart.y < swipeScroll.touches.touchmove.y) {
swipeScroll.up();
} else {
swipeScroll.down();
}
}
}
}
}
break;
case 'touchend':
if(swipeScroll.touches[event.type]===false) {
swipeScroll.touches[event.type] = true;
if (swipeScroll.touches.touchstart.y > -1 && swipeScroll.touches.touchmove.y > -1 && swipeScroll.touches.direction==="y") {
if(Math.abs(swipeScroll.touches.touchmove.y-swipeScroll.touches.touchstart.y)>swipeScroll.options.distance) {
if(swipeScroll.touches.touchstart.y < swipeScroll.touches.touchmove.y) {
swipeScroll.up();
} else {
swipeScroll.down();
}
}
swipeScroll.touches.touchstart.y = -1;
swipeScroll.touches.touchstart.x = -1;
swipeScroll.touches.direction = "undetermined";
}
}
default:
break;
}
}
}
},
down: function() {
if(index<=heights.length-1) {
if(atBottom() && index<heights.length-1) {
index++;
//index, instant, callbacks
animateScroll(index,false,true);
} else {
if(Math.floor(elements[index].height()/$window.height())>interstitialIndex) {
interstitialScroll(parseInt(heights[index])+($window.height()*interstitialIndex));
interstitialIndex += 1;
} else {
interstitialScroll(parseInt(heights[index])+(elements[index].height()-$window.height()));
}
}
}
},
up: function() {
if(index>=0) {
if(atTop() && index>0) {
index--;
//index, instant, callbacks
animateScroll(index,false,true);
} else {
if(interstitialIndex>2) {
interstitialIndex -= 1;
interstitialScroll(parseInt(heights[index])+($window.height()*interstitialIndex));
} else {
interstitialIndex = 1;
interstitialScroll(parseInt(heights[index]));
}
}
}
},
init: function() {
if (document.addEventListener) {
document.addEventListener('touchstart', swipeScroll.touchHandler, false);
document.addEventListener('touchmove', swipeScroll.touchHandler, false);
document.addEventListener('touchend', swipeScroll.touchHandler, false);
}
}
};
util = {
refresh:function(withCallback) {
clearTimeout(timeoutId2);
timeoutId2 = setTimeout(function() {
sizePanels();
calculatePositions(true);
if(withCallback) {
settings.afterResize();
}
},400);
},
handleUpdate:function() {
util.refresh(false);
},
handleResize:function() {
util.refresh(true);
}
};
settings = $.extend(settings, options);
sizePanels();
calculatePositions(false);
if(true===hasLocation) {
//index, instant, callbacks
animateScroll(index,false,true);
} else {
setTimeout(function() {
//instant,callbacks
manualScroll.calculateNearest(true,false);
},200);
}
if(heights.length) {
manualScroll.init();
swipeScroll.init();
$window.on("resize",util.handleResize);
if (document.addEventListener) {
window.addEventListener("orientationchange", util.handleResize, false);
}
}
function interstitialScroll(pos) {
if( $().velocity ) {
$(settings.target).stop().velocity('scroll', {
duration: settings.scrollSpeed,
easing: settings.easing,
offset: pos,
mobileHA: false
});
} else {
$(settings.target).stop().animate({
scrollTop: pos
}, settings.scrollSpeed,settings.easing);
}
}
function sizePanels() {
var selector = settings.section;
overflow = [];
if(settings.interstitialSection.length) {
selector += "," + settings.interstitialSection;
}
$(selector).each(function(i) {
var $this = $(this);
if(settings.setHeights) {
if($this.is(settings.interstitialSection)) {
overflow[i] = false;
} else {
if(($this.css("height","auto").outerHeight()<$window.height()) || $this.css("overflow")==="hidden") {
$this.css({"height":$window.height()});
overflow[i] = false;
} else {
$this.css({"height":$this.height()});
if(settings.overflowScroll) {
overflow[i] = true;
} else {
overflow[i] = false;
}
}
}
} else {
if(($this.outerHeight()<$window.height()) || (settings.overflowScroll===false)) {
overflow[i] = false;
} else {
overflow[i] = true;
}
}
});
}
function calculatePositions(resize) {
var selector = settings.section;
if(settings.interstitialSection.length) {
selector += "," + settings.interstitialSection;
}
heights = [];
names = [];
elements = [];
$(selector).each(function(i){
var $this = $(this);
if(i>0) {
heights[i] = parseInt($this.offset().top) + settings.offset;
} else {
heights[i] = parseInt($this.offset().top);
}
if(settings.sectionName && $this.data(settings.sectionName)) {
names[i] = "#" + $this.data(settings.sectionName).replace(/ /g,"-");
} else {
if($this.is(settings.interstitialSection)===false) {
names[i] = "#" + (i + 1);
} else {
names[i] = "#";
if(i===$(selector).length-1 && i>1) {
heights[i] = heights[i-1]+parseInt($this.height());
}
}
}
elements[i] = $this;
try {
if($(names[i]).length && window.console) {
console.warn("Scrollify warning: Section names can't match IDs on the page - this will cause the browser to anchor.");
}
} catch (e) {}
if(window.location.hash===names[i]) {
index = i;
hasLocation = true;
}
});
if(true===resize) {
//index, instant, callbacks
animateScroll(index,false,false);
} else {
settings.afterRender();
}
}
function atTop() {
if(!overflow[index]) {
return true;
}
top = $window.scrollTop();
if(top>parseInt(heights[index])) {
return false;
} else {
return true;
}
}
function atBottom() {
if(!overflow[index]) {
return true;
}
top = $window.scrollTop();
if(top<parseInt(heights[index])+(elements[index].outerHeight()-$window.height())-28) {
return false;
} else {
return true;
}
}
}
function move(panel,instant) {
var z = names.length;
for(;z>=0;z--) {
if(typeof panel === 'string') {
if (names[z]===panel) {
index = z;
//index, instant, callbacks
animateScroll(z,instant,true);
}
} else {
if(z===panel) {
index = z;
//index, instant, callbacks
animateScroll(z,instant,true);
}
}
}
}
$.scrollify.move = function(panel) {
if(panel===undefined) {
return false;
}
if(panel.originalEvent) {
panel = $(this).attr("href");
}
move(panel,false);
};
$.scrollify.instantMove = function(panel) {
if(panel===undefined) {
return false;
}
move(panel,true);
};
$.scrollify.next = function() {
if(index<names.length) {
index += 1;
animateScroll(index,false,true);
}
};
$.scrollify.previous = function() {
if(index>0) {
index -= 1;
//index, instant, callbacks
animateScroll(index,false,true);
}
};
$.scrollify.instantNext = function() {
if(index<names.length) {
index += 1;
//index, instant, callbacks
animateScroll(index,true,true);
}
};
$.scrollify.instantPrevious = function() {
if(index>0) {
index -= 1;
//index, instant, callbacks
animateScroll(index,true,true);
}
};
$.scrollify.destroy = function() {
if(!initialised) {
return false;
}
if(settings.setHeights) {
$(settings.section).each(function() {
$(this).css("height","auto");
});
}
$window.off("resize",util.handleResize);
if(settings.scrollbars) {
$window.off('mousedown', manualScroll.handleMousedown);
$window.off('mouseup', manualScroll.handleMouseup);
$window.off('scroll', manualScroll.handleScroll);
}
$window.off(wheelEvent,manualScroll.wheelHandler);
$window.off('keydown', manualScroll.keyHandler);
if (document.addEventListener) {
document.removeEventListener('touchstart', swipeScroll.touchHandler, false);
document.removeEventListener('touchmove', swipeScroll.touchHandler, false);
document.removeEventListener('touchend', swipeScroll.touchHandler, false);
}
heights = [];
names = [];
elements = [];
overflow = [];
};
$.scrollify.update = function() {
if(!initialised) {
return false;
}
util.handleUpdate();
};
$.scrollify.current = function() {
return elements[index];
};
$.scrollify.disable = function() {
disabled = true;
};
$.scrollify.enable = function() {
disabled = false;
if (initialised) {
//instant,callbacks
manualScroll.calculateNearest(false,false);
}
};
$.scrollify.isDisabled = function() {
return disabled;
};
$.scrollify.setOptions = function(updatedOptions) {
if(!initialised) {
return false;
}
if(typeof updatedOptions === "object") {
settings = $.extend(settings, updatedOptions);
util.handleUpdate();
} else if(window.console) {
console.warn("Scrollify warning: Options need to be in an object.");
}
};
}));
I think you are listening wrong event. Use keydown event this will work.
working fiddle

How to go faster than a short setTimeout in javascript?

How to make a script repeat it self faster than a setTimeout allows but still not as fast as possible?
Check this demo for 2 examples.
(I post the demo code under also)
var x = 0;
var divEl = document.getElementById('counter');
var divEl2 = document.getElementById('counter2');
document.getElementById('gosettimeout').addEventListener('click', go, false);
document.getElementById('gotoofast').addEventListener('click', go2, false);
function go() {
x++;
divEl.innerHTML = x;
if (x > 100) {
return false;
}
setTimeout(function () {
go();
}, 0);
}
function go2() {
x++;
divEl2.innerHTML = x;
if (x > 100) {
return false;
}
go2();
}
var x = 0;
var divEl = document.getElementById('counter');
var divEl2 = document.getElementById('counter2');
document.getElementById('gosettimeout').addEventListener('click', go, false);
document.getElementById('gotoofast').addEventListener('click', go2, false);
function go() {
x++;
divEl.innerHTML = x;
if (x > 100) {
return false;
}
if (x % 2 == 0) {
setTimeout(function () {
go();
}, 0);
} else {
go();
}
}
function go2() {
x++;
divEl2.innerHTML = x;
if (x > 100) {
return false;
}
go2();
}
Two times faster, but not as fast as possible =)
var x = 0;
var divEl = document.getElementById('counter');
var divEl2 = document.getElementById('counter2');
document.getElementById('gosettimeout').addEventListener('click', go, false);
document.getElementById('gotoofast').addEventListener('click', go2, false);
function go() {
divEl.innerHTML = ++x;
if (x > 100) {
return false;
}
if (x % 5 == 0) {
setTimeout(function () {
go();
}, 0);
} else {
go();
}
}
function go2() {
x++;
divEl2.innerHTML = x;
if (x > 100) {
return false;
}
go2();
}

Categories

Resources