Scolling a div up and down - javascript

I have set up a fiddle
http://jsfiddle.net/austinind/aadcd/1/
what I am trying to achieve is a parallax effect.
the div should scoll up and down based on the scolling.
in my case the div only scrolls up:
function parallax(){
var scrolled = $(window).scrollTop();
var elempos=$(".bg2").position().top;
$('.bg2').css('top', elempos-(scrolled * 0.2) + 'px');
}
$(window).scroll(function(e){
parallax();
});

Take a look at following Js fiddle
Javscript for scroll
(function($) {
var types = ['DOMMouseScroll', 'mousewheel'];
if ($.event.fixHooks) {
for ( var i=types.length; i; ) {
$.event.fixHooks[ types[--i] ] = $.event.mouseHooks;
}
}
$.event.special.mousewheel = {
setup: function() {
if ( this.addEventListener ) {
for ( var i=types.length; i; ) {
this.addEventListener( types[--i], handler, false );
}
} else {
this.onmousewheel = handler;
}
},
teardown: function() {
if ( this.removeEventListener ) {
for ( var i=types.length; i; ) {
this.removeEventListener( types[--i], handler, false );
}
} else {
this.onmousewheel = null;
}
}
};
$.fn.extend({
mousewheel: function(fn) {
return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
},
unmousewheel: function(fn) {
return this.unbind("mousewheel", fn);
}
});
function handler(event) {
var orgEvent = event || window.event, args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true, deltaX = 0, deltaY = 0;
event = $.event.fix(orgEvent);
event.type = "mousewheel";
// Old school scrollwheel delta
if ( orgEvent.wheelDelta ) { delta = orgEvent.wheelDelta/120; }
if ( orgEvent.detail ) { delta = -orgEvent.detail/3; }
// New school multidimensional scroll (touchpads) deltas
deltaY = delta;
// Gecko
if ( orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
deltaY = 0;
deltaX = -1*delta;
}
// Webkit
if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY/120; }
if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = -1*orgEvent.wheelDeltaX/120; }
// Add event and delta to the front of the arguments
args.unshift(event, delta, deltaX, deltaY);
return ($.event.dispatch || $.event.handle).apply(this, args);
}
})(jQuery);
// OUR CODE
var winH = $(window).height();
$('.page').height(winH);
var c = 0;
var pagesN = $('.page').length;
$(document).bind('mousewheel', function(ev, delta) {
delta>0 ? --c : ++c ;
if(c===-1){
c=0;
}else if(c===pagesN){
c=pagesN-1;
}
var pagePos = $('.page').eq(c).position().top;
$('html, body').stop().animate({scrollTop: pagePos},1000);
return false;
});

Your script is working fine, your actual problem is your CSS
Remove
position:Fixed
for the class bg2, And it will work fine
Fiddle
http://jsfiddle.net/AmarnathRShenoy/aadcd/2/

Related

Block a JavaScript function in a page

I have a javascript function for a slider in the JS file of my site. When we are in a page where the slider is not called or there is no trigger element, it displays an error in the console "Uncaught TypeError: Cannot read properties of null (reading 'querySelector') ", This error is not displayed when the slider is in the page.
I would like to know how to avoid this error, and how to prevent this function from loading in pages where this slider is not present?
function slider(set) {
const sliderContainer = document.querySelector(set.name),
slider = sliderContainer.querySelector('.slider'),
sliderItem = slider.querySelectorAll('.slider__item'),
sliderArrows = sliderContainer.querySelectorAll('.arrows__item');
let dotsCreate,
dotsClass,
dotsFunk,
numberSlider,
numberSliderWork,
sliderExecutionLine,
sliderExecutionLineWork;
// calculate the maximum width of all slides
function forSliderItem(t) {
t = 0;
for(let i = 0; i < sliderItem.length - 1; i++) {
t += sliderItem[i].clientWidth;
}
return t;
}
let maxWidth = forSliderItem(sliderItem), // maximum width of all slides
slidWidth = 0, // main variable for calculating the movement of the slider
count = 0; // counter
//===== flip left
sliderArrows[0].addEventListener('click', function() {
if(count !== 0) {
count--;
slidWidth -= sliderItem[count].clientWidth;
slider.style.transform = `translateX(-${slidWidth}px)`;
} else {
count = sliderItem.length - 1;
slidWidth = maxWidth;
slider.style.transform = `translateX(-${slidWidth}px)`;
}
if(set.dots) {
dotsFunk();
}
if(set.numberSlid) {
numberSliderWork(count);
}
if(set.line) {
sliderExecutionLineWork(count);
}
});
//===== flip right
sliderArrows[1].addEventListener('click', function() {
if(count < sliderItem.length - 1) {
count++;
slidWidth += sliderItem[count].clientWidth;
slider.style.transform = `translateX(-${slidWidth}px)`;
} else {
count = 0;
slidWidth = 0;
slider.style.transform = `translateX(-${slidWidth}px)`;
}
if(set.dots) {
dotsFunk();
}
if(set.numberSlid) {
numberSliderWork(count);
}
if(set.line) {
sliderExecutionLineWork(count);
}
});
//===== dots
if(set.dots) {
dotsCreate = function() {
const dotContainer = document.createElement('div'); // create dots container
dotContainer.classList.add('dots');
// create the required number of dots and insert a container into the dots
sliderItem.forEach(() => {
let dotsItem = document.createElement('span');
dotContainer.append(dotsItem);
});
sliderContainer.append(dotContainer);
};
dotsCreate();
// add the class to the desired dots, and remove from the rest
dotsClass = function(remove, add) {
remove.classList.remove('dots_active');
add.classList.add('dots_active');
};
// move slides by clicking on the dot
dotsFunk = function() {
const dotsWork = sliderContainer.querySelectorAll('.dots span'); // we get dots
dotsWork.forEach((item, i) => {
dotsClass(dotsWork[i], dotsWork[count]);
item.addEventListener('click', function() {
count = i;
// multiply the slide size by the number of the dots, and get the number by which you need to move the slider
slidWidth = sliderItem[0].clientWidth * i;
slider.style.transform = `translateX(-${slidWidth}px)`;
for(let j = 0; j < dotsWork.length; j++) {
dotsClass(dotsWork[j], dotsWork[count]);
}
if(set.dots && set.numberSlid) {
numberSliderWork(count);
}
if(set.line) {
sliderExecutionLineWork(count);
}
});
});
};
dotsFunk();
}
//===== count slider
if(set.numberSlid) {
numberSlider = function(item) {
const countContainer = document.createElement('div'),
sliderNumber = document.createElement('span'),
slash = document.createElement('span'),
allSliderNumber = document.createElement('span');
casClient = document.createElement('p');
sliderNumber.innerHTML = item + 1;
casClient.innerHTML = 'Cas client N°';
slash.innerHTML = '/';
allSliderNumber.innerHTML = sliderItem.length;
countContainer.classList.add('count-slides');
countContainer.append(casClient, sliderNumber, slash, allSliderNumber);
sliderContainer.append(countContainer);
};
numberSlider(0);
numberSliderWork = function(item) {
const sliderNumberNow = sliderContainer.querySelector('.count-slides span');
sliderNumberNow.innerHTML = item + 1;
if(set.line) {
sliderExecutionLineWork(item);
}
};
}
}
slider({
name: ".video_users",
numberSlid: true
});
<!DOCTYPE html>
<html lang="fr">
<head>
<title>Example of a page without the slider</title>
</head>
<body class="error_404">
<h1>Example of a page without the slider</h1>
<script src="media/js/faveod.js" async></script>
</body>
</html>
Just return if the element isn't present if you don't want it to show an error.
const sliderContainer = document.querySelector(set.name);
if (!sliderContainer) return;
const slider = sliderContainer.querySelector('.slider'),
sliderItem = slider.querySelectorAll('.slider__item'),
sliderArrows = sliderContainer.querySelectorAll('.arrows__item');
If you want it to only execute on certain pages, then just add:
if (location.pathname !== '/the/page/with/slider') return;
to the beginning of the function
/*
* SCROLLBAR 2 COLUMN / SOLUTIONS
*/
var ssb = {
aConts : [],
mouseY : 0,
N : 0,
asd : 0, /*active scrollbar element*/
sc : 0,
sp : 0,
to : 0,
// constructor
scrollbar : function (cont_id) {
var cont = document.getElementById(cont_id);
// perform initialization
if (! ssb.init()) return false;
var cont_clone = cont.cloneNode(false);
cont_clone.style.overflow = "hidden";
cont.parentNode.appendChild(cont_clone);
cont_clone.appendChild(cont);
cont.style.position = 'absolute';
cont.style.left = cont.style.top = '0px';
cont.style.width = cont.style.height = '100%';
// adding new container into array
ssb.aConts[ssb.N++] = cont;
cont.sg = false;
//creating scrollbar child elements
cont.st = this.create_div('ssb_st', cont, cont_clone);
cont.sb = this.create_div('ssb_sb', cont, cont_clone);
cont.su = this.create_div('ssb_up', cont, cont_clone);
cont.sd = this.create_div('ssb_down', cont, cont_clone);
// on mouse down processing
cont.sb.onmousedown = function (e) {
if (! this.cont.sg) {
if (! e) e = window.event;
ssb.asd = this.cont;
this.cont.yZ = e.screenY;
this.cont.sZ = cont.scrollTop;
this.cont.sg = true;
// new class name
this.className = 'ssb_sb ssb_sb_down';
}
return false;
}
// on mouse down on free track area - move our scroll element too
cont.st.onmousedown = function (e) {
if (! e) e = window.event;
ssb.asd = this.cont;
ssb.mouseY = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
for (var o = this.cont, y = 0; o != null; o = o.offsetParent) y += o.offsetTop;
this.cont.scrollTop = (ssb.mouseY - y - (this.cont.ratio * this.cont.offsetHeight / 2) - this.cont.sw) / this.cont.ratio;
this.cont.sb.onmousedown(e);
}
// onmousedown events
cont.su.onmousedown = cont.su.ondblclick = function (e) { ssb.mousedown(this, -1); return false; }
cont.sd.onmousedown = cont.sd.ondblclick = function (e) { ssb.mousedown(this, 1); return false; }
//onmouseout events
cont.su.onmouseout = cont.su.onmouseup = ssb.clear;
cont.sd.onmouseout = cont.sd.onmouseup = ssb.clear;
// on mouse over - apply custom class name: ssb_sb_over
cont.sb.onmouseover = function (e) {
if (! this.cont.sg) this.className = 'ssb_sb ssb_sb_over';
return false;
}
// on mouse out - revert back our usual class name 'ssb_sb'
cont.sb.onmouseout = function (e) {
if (! this.cont.sg) this.className = 'ssb_sb';
return false;
}
// onscroll - change positions of scroll element
cont.ssb_onscroll = function () {
this.ratio = (this.offsetHeight - 2 * this.sw) / this.scrollHeight;
this.sb.style.top = Math.floor(this.sw + this.scrollTop * this.ratio) + 'px';
}
// scrollbar width
cont.sw = 16;
// start scrolling
cont.ssb_onscroll();
ssb.refresh();
// binding own onscroll event
cont.onscroll = cont.ssb_onscroll;
return cont;
},
// initialization
init : function () {
if (window.oper || (! window.addEventListener && ! window.attachEvent)) { return false; }
// temp inner function for event registration
function addEvent (o, e, f) {
if (window.addEventListener) { o.addEventListener(e, f, false); ssb.w3c = true; return true; }
if (window.attachEvent) return o.attachEvent('on' + e, f);
return false;
}
// binding events
addEvent(window.document, 'mousemove', ssb.onmousemove);
addEvent(window.document, 'mouseup', ssb.onmouseup);
addEvent(window, 'resize', ssb.refresh);
return true;
},
// create and append div finc
create_div : function(c, cont, cont_clone) {
var o = document.createElement('div');
o.cont = cont;
o.className = c;
cont_clone.appendChild(o);
return o;
},
// do clear of controls
clear : function () {
clearTimeout(ssb.to);
ssb.sc = 0;
return false;
},
// refresh scrollbar
refresh : function () {
for (var i = 0, N = ssb.N; i < N; i++) {
var o = ssb.aConts[i];
o.ssb_onscroll();
o.sb.style.width = o.st.style.width = o.su.style.width = o.su.style.height = o.sd.style.width = o.sd.style.height = o.sw + 'px';
o.sb.style.height = Math.ceil(Math.max(o.sw * .5, o.ratio * o.offsetHeight) + 1) + 'px';
}
},
// arrow scrolling
arrow_scroll : function () {
if (ssb.sc != 0) {
ssb.asd.scrollTop += 6 * ssb.sc / ssb.asd.ratio;
ssb.to = setTimeout(ssb.arrow_scroll, ssb.sp);
ssb.sp = 32;
}
},
/* event binded functions : */
// scroll on mouse down
mousedown : function (o, s) {
if (ssb.sc == 0) {
// new class name
o.cont.sb.className = 'ssb_sb ssb_sb_down';
ssb.asd = o.cont;
ssb.sc = s;
ssb.sp = 100;
ssb.arrow_scroll();
}
},
// on mouseMove binded event
onmousemove : function(e) {
if (! e) e = window.event;
// get vertical mouse position
ssb.mouseY = e.screenY;
if (ssb.asd.sg) ssb.asd.scrollTop = ssb.asd.sZ + (ssb.mouseY - ssb.asd.yZ) / ssb.asd.ratio;
},
// on mouseUp binded event
onmouseup : function (e) {
if (! e) e = window.event;
var tg = (e.target) ? e.target : e.srcElement;
if (ssb.asd && document.releaseCapture) ssb.asd.releaseCapture();
// new class name
if (ssb.asd) ssb.asd.sb.className = (tg.className.indexOf('scrollbar') > 0) ? 'ssb_sb ssb_sb_over' : 'ssb_sb';
document.onselectstart = '';
ssb.clear();
ssb.asd.sg = false;
}
}
window.onload = function() {
ssb.scrollbar('container'); // scrollbar initialization
}

Scroll to top button wont fadeOut

I am having trouble getting my scroll to top button to work. I know its a problem with another animation but I am not able to see what is causing the issue. The problem is when the other animation "starts when scroll hits 500" the scroll to top button will no longer fade out and disappear.
$.chain = function() {
var promise = $.Deferred().resolve().promise();
jQuery.each( arguments, function() {
promise = promise.pipe( this );
});
return promise;
};
function scrollTop(){
if(typeof pageYOffset!= 'undefined'){
return pageYOffset;
}
else{
var b = document.body; //IE 'quirks'
var d = document.documentElement; //IE with doctype
d = (d.clientHeight)? d : b;
return d.scrollTop;
}
}
$(window).on("scroll", function(){
if(scrollTop() >= 600){
$(window).off("scroll");
var animations = $.chain(function() {
return $('#animate1 img').fadeIn('slow').delay(400);
}, function() {
return $('#animate2 img').fadeIn('slow').delay(400);
}, function() {
return $('#animate3 img').fadeIn('slow');
});
};
});
jQuery(document).ready(function() {
var offset = 300;
var duration = 500;
jQuery(window).scroll(function() {
if (jQuery(this).scrollTop() > offset) {
jQuery('.scroll-top').fadeIn(duration);
} else {
jQuery('.scroll-top').fadeOut(duration);
}
});
});
Thank you for any help.
$(window).off("scroll"); is indeed removing scroll event which you're listening to fadeIn and fadeOut.
Although i havent tried it but an alternative would be to use event namespacing?
something like below:
$.chain = function() {
var promise = $.Deferred().resolve().promise();
jQuery.each( arguments, function() {
promise = promise.pipe( this );
});
return promise;
};
function scrollTop(){
if(typeof pageYOffset!= 'undefined'){
return pageYOffset;
}
else{
var b = document.body; //IE 'quirks'
var d = document.documentElement; //IE with doctype
d = (d.clientHeight)? d : b;
return d.scrollTop;
}
}
$(window).on("scroll.foranimations", function(){ // event name
if(scrollTop() >= 600){
$(window).off("scroll.foranimations"); // event name
var animations = $.chain(function() {
return $('#animate1 img').fadeIn('slow').delay(400);
}, function() {
return $('#animate2 img').fadeIn('slow').delay(400);
}, function() {
return $('#animate3 img').fadeIn('slow');
});
};
});
jQuery(document).ready(function() {
var offset = 300;
var duration = 500;
jQuery(window).on("scroll.forfading", function() { // event name
if (jQuery(this).scrollTop() > offset) {
jQuery('.scroll-top').fadeIn(duration);
} else {
jQuery('.scroll-top').fadeOut(duration);
}
});
});
notice different event names scroll.foranimations and scroll.forfading

Isotope js detect first/last child in a row

How to detect first/last child in a row via isotope js?
I want to remove margins between elements.
This is layout.` // ====================== fitRows ======================
_fitRowsReset : function() {
this.fitRows = {
x : 0,
y : 0,
height : 0
};
},
_fitRowsLayout : function( $elems ) {
var instance = this,
containerWidth = this.element.width(),
props = this.fitRows;
$elems.each( function() {
var $this = $(this),
atomW = $this.outerWidth(true),
atomH = $this.outerHeight(true);
if ( props.x !== 0 && atomW + props.x > containerWidth ) {
// if this element cannot fit in the current row
props.x = 0;
props.y = props.height;
}
// position the atom
instance._pushPosition( $this, props.x, props.y );
props.height = Math.max( props.y + atomH, props.height );
props.x += atomW;
});
},
_fitRowsGetContainerSize : function () {
return { height : this.fitRows.height };
},
_fitRowsResizeChanged : function() {
return true;
},
`
Solution is simple
// ====================== fitRows ======================
_fitRowsReset : function() {
this.fitRows = {
x : 0,
y : 0,
height : 0
};
},
_fitRowsLayout : function( $elems ) {
var instance = this,
containerWidth = this.element.width(),
props = this.fitRows;
$elems.each( function() {
var $this = $(this),
atomW = $this.outerWidth(true),
atomH = $this.outerHeight(true);
$(this).removeClass('first last');
if (props.x == 0) {
$(this).addClass('first');
$(this).prev().addClass('last');
}
if ( props.x !== 0 && atomW + props.x > containerWidth ) {
// if this element cannot fit in the current row
props.x = 0;
props.y = props.height;
$(this).addClass('first');
$(this).prev().addClass('last');
}
// position the atom
instance._pushPosition( $this, props.x, props.y );
props.height = Math.max( props.y + atomH, props.height );
props.x += atomW;
});
},
_fitRowsGetContainerSize : function () {
return { height : this.fitRows.height };
},
_fitRowsResizeChanged : function() {
return true;
},

Touch events on iPhone

I am trying to make an off-canvas menu that can be opened systematically on touch events. It works fine on my browser when I click on the body and drag it to open the menu.
However it fails on the iPhone. The error that is being displayed on my console is
TypeError: 'undefined' is not an object (evaluating 'event.touches[0]')
which is on this function:
getTouchCoordinates: function(event) {
if ( s.touchSupported ) {
var touchEvent = event.touches[0];
return { x:touchEvent.pageX, y:touchEvent.pageY }
}
else {
return { x:event.screenX, y:event.screenY };
}
},
The full codes of the menu is as follows:
document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
var s,
app = {
settings: {
touchSupported: ('ontouchstart' in window),
start_event: "",
move_event: "",
end_event: "",
main: $("#body"),
sidebar: $("#sidebar"),
gestureStarted: false,
bodyOffset: 0,
sidebarWidth: 250,
gestureStartPosition: "",
gestureS: "",
target: ""
},
init: function() {
s = this.settings;
this.touchHandlers();
this.bindUIActions();
},
bindUIActions: function() {
s.main.bind(s.start_event, function(e){
s.gestureStartPosition = app.getTouchCoordinates(e);
s.gestureS = app.getTouchCoordinates(e);
s.main.bind(s.move_event, function(e){
var pos = app.getTouchCoordinates(e);
var currentPosition = app.getTouchCoordinates( event );
if ( s.gestureStarted ) {
event.preventDefault();
event.stopPropagation();
app.updateBasedOnTouchPoints( currentPosition.x );
return;
}
else {
if ( Math.abs( currentPosition.y - s.gestureStartPosition.y ) > 50 ) {
//unbind events here
s.main.unbind(s.end_event);
s.main.unbind(s.move_event);
return;
}
else if ( Math.abs( currentPosition.x - s.gestureStartPosition.x ) > 0 ) {
s.gestureStarted = true;
event.preventDefault();
event.stopPropagation();
app.updateBasedOnTouchPoints( currentPosition.x );
return;
}
}
});
s.main.bind(s.end_event, function(e){
var currentPosition = app.getTouchCoordinates( event );
if ( s.gestureStarted ) {
s.main.css("left", "0px" );
//console.log(s.gestureS.x+" "+currentPosition.x);
var c = s.bodyOffset ;
var t;
// check if open or close
if ( (s.gestureS.x - currentPosition.x) < 0 ) {
//console.log("open");
t = s.sidebarWidth;
} else {
//console.log("close");
t = 0 ;
}
if ( c != t ) {
s.main.stop(true, false).animate({
left:t,
avoidTransforms:false,
useTranslate3d: true
}, 100);
s.sidebar.trigger( "slidingViewProgress", { current:t, max:s.sidebarWidth } );
}
}
s.gestureStarted = false;
//unbind events here
s.main.unbind(s.end_event);
s.main.unbind(s.move_event);
});
});
},
touchHandlers: function() {
s.start_event = s.touchSupported ? 'touchstart' : 'mousedown';
s.move_event = s.touchSupported ? 'touchmove' : 'mousemove';
s.end_event = s.touchSupported ? 'touchend' : 'mouseup';
},
getTouchCoordinates: function(event) {
if ( s.touchSupported ) {
var touchEvent = event.touches[0];
return { x:touchEvent.pageX, y:touchEvent.pageY }
}
else {
return { x:event.screenX, y:event.screenY };
}
},
updateBasedOnTouchPoints: function( currentPosition ) {
var deltaX = (currentPosition - s.gestureStartPosition.x) ;
var targetX = (s.bodyOffset + deltaX);
targetX = Math.max( targetX, 0 );
targetX = Math.min( targetX, s.sidebarWidth );
s.bodyOffset = targetX;
s.target = targetX;
if ( s.main.css("left") != "0px" ) {
s.main.css("left", "0px" );
}
s.main.css("-webkit-transform", "translate3d(" + targetX + "px,0,0)" );
s.main.css("-moz-transform", "translate3d(" + targetX + "px,0,0)" );
s.main.css("transform", "translate3d(" + targetX + "px,0,0)" );
s.sidebar.trigger( "slidingViewProgress", { current: targetX, max:s.sidebarWidth } );
s.gestureStartPosition.x = currentPosition;
}
};
(function() {
app.init();
})();
Can you try:
event.originalEvent.touches

Extend Zepto.js with a jQuery method? scrollTop()

I'm using Zepto.js on a current project. Zepto doesn't support the scrollTop() method that jQuery has in it.
Is it possible to kind of extend Zepto to work with scrollTop() too?
Update: All I want is to create my own small and simple "animated scroll" function like I have used before with jQuery. See the working example here. However I have no idea how to make the same function work without the scrollTop() function available in Zepto.js.
scrollTop isn't animatable using Zepto's .animate method, as it uses CSS transitions.
Try something like this: http://jsfiddle.net/DVDLM/5/
function scroll(scrollTo, time) {
var scrollFrom = parseInt(document.body.scrollTop),
i = 0,
runEvery = 5; // run every 5ms
scrollTo = parseInt(scrollTo);
time /= runEvery;
var interval = setInterval(function () {
i++;
document.body.scrollTop = (scrollTo - scrollFrom) / time * i + scrollFrom;
if (i >= time) {
clearInterval(interval);
}
}, runEvery);
}
$('#trigger').click(function () {
scroll('600px', 500);
});
EDIT: I added a runEvery variable, which specifies how often the interval should be ran. The lower this is, the smoother the animation is, but it could affect performance.
EDIT2: I think I misread the question. Here is the answer to the new question:
$.zepto.scrollTop = function (pixels) {
this[0].scrollTop = pixels;
};
dont want to steel nobody work so here is the short answer
Porting from jQuery to Zepto
Use the DOM native scrollTop property:
$('#el')[0].scrollTop = 0;
(function ($) {
['width', 'height'].forEach(function(dimension) {
var offset, Dimension = dimension.replace(/./, function(m) { return m[0].toUpperCase() });
$.fn['outer' + Dimension] = function(margin) {
var elem = this;
if (elem) {
var size = elem[dimension]();
var sides = {'width': ['left', 'right'], 'height': ['top', 'bottom']};
sides[dimension].forEach(function(side) {
if (margin) size += parseInt(elem.css('margin-' + side), 10);
});
return size;
}
else {
return null;
}
};
});
["Left", "Top"].forEach(function(name, i) {
var method = "scroll" + name;
function isWindow( obj ) {
return obj && typeof obj === "object" && "setInterval" in obj;
}
function getWindow( elem ) {
return isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false;
}
$.fn[method] = function( val ) {
var elem, win;
if (val === undefined) {
elem = this[0];
if (!elem) {
return null;
}
win = getWindow(elem);
// Return the scroll offset
return win ? ("pageXOffset" in win) ? win[i ? "pageYOffset" : "pageXOffset"] :
win.document.documentElement[method] ||
win.document.body[method] :
elem[method];
}
// Set the scroll offset
this.each(function() {
win = getWindow(this);
if (win) {
var xCoord = !i ? val : $(win).scrollLeft();
var yCoord = i ? val : $(win).scrollTop();
win.scrollTo(xCoord, yCoord);
}
else {
this[method] = val;
}
});
}
});
})(Zepto);
The answer is simple, Zepto dose not use timeout style animation, it uses css3, so here is a basic implementation for a scroll function:
HTML:
Animated Scroll
Hello You
​
CSS:
#page { height:5000px; position:relative; }
#element { position:absolute; top:600px }
JS:
function scroll(selector, animate, viewOffset) {
$('body').scrollToBottom (600, '800');
}
$('#trigger').click(function(e) {
e.preventDefault();
scroll( $('#element'), true, 30 );
});
$.fn.scrollToBottom = function(scrollHeight ,duration) {
var $el = this;
var el = $el[0];
var startPosition = el.scrollTop;
var delta = scrollHeight - startPosition;
var startTime = Date.now();
function scroll() {
var fraction = Math.min(1, (Date.now() - startTime) / duration);
el.scrollTop = delta * fraction + startPosition;
if(fraction < 1) {
setTimeout(scroll, 10);
}
}
scroll();
};
​
Note that version 1.0 of Zeptos now supports scrollTop(). See Documentation:
http://zeptojs.com/#scrollTop

Categories