I am a total newbie in Webpack which I have started to use 3 days ago to change how we load our javascript.
The code before webpack, which is working, is used to implement a "famous" fading effect (source gist.github.com/paulirish/1579671)
window.requestNextAnimationFrame =
(function () {
var originalWebkitRequestAnimationFrame = undefined,
wrapper = undefined,
callback = undefined,
geckoVersion = 0,
userAgent = navigator.userAgent,
index = 0,
self = this;
// Workaround for Chrome 10 bug where Chrome
// does not pass the time to the animation function
if (window.webkitRequestAnimationFrame) {
// Define the wrapper
wrapper = function (time) {
if (time === undefined) {
time = +new Date();
}
self.callback(time);
};
// Make the switch
originalWebkitRequestAnimationFrame = window.webkitRequestAnimationFrame;
window.webkitRequestAnimationFrame = function (callback, element) {
self.callback = callback;
// Browser calls the wrapper and wrapper calls the callback
originalWebkitRequestAnimationFrame(wrapper, element);
}
}
// Workaround for Gecko 2.0, which has a bug in
// mozRequestAnimationFrame() that restricts animations
// to 30-40 fps.
if (window.mozRequestAnimationFrame) {
// Check the Gecko version. Gecko is used by browsers
// other than Firefox. Gecko 2.0 corresponds to
// Firefox 4.0.
index = userAgent.indexOf('rv:');
if (userAgent.indexOf('Gecko') != -1) {
geckoVersion = userAgent.substr(index + 3, 3);
if (geckoVersion === '2.0') {
// Forces the return statement to fall through
// to the setTimeout() function.
window.mozRequestAnimationFrame = undefined;
}
}
}
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback, element) {
var start,
finish;
window.setTimeout( function () {
start = +new Date();
callback(start);
finish = +new Date();
self.timeout = 1000 / 60 - (finish - start);
}, self.timeout);
};
}
)
();
// It's then used here in our code here:
loadIcons();
function loadCompanyIcons() {
var elements = document.querySelectorAll('img');
if (!elements) return;
Array.prototype.forEach.call(elements, function(el, i){
var watcher = scrollMonitor.create(el, 2000);
watcher.enterViewport(function() {
var srcToInject = el.getAttribute('data-src');
var src = el.getAttribute('src');
if (src === null && srcToInject!=null) { // do not re-execute for images already with injected src
el.style.opacity = 0;
el.style.display = "block";
el.setAttribute('src',srcToInject);
el.onload = imageFound;
el.onerror = imageNotFound;
function imageFound() {
// progressively show image via opacity variation
(function fade() {
var val = parseFloat(el.style.opacity);
if (!((val += .1) > 1)) {
el.style.opacity = val;
requestNextAnimationFrame(fade);
}
})();
}
}
});
});
}
It perfectly works when used on a basic js file.
When we tried to move to Webpack and use "exports" we hit a wall. Most Webapck export we do have been working so I think this one does not work because it's not a standard:
function doSth() {
}
But it starts with window.doSth()...
Here's what we do today which is failing:
js/helpers/requestAnimationFramePolyfill.js
export window.requestNextAnimationFrame =
(function () {
var originalWebkitRequestAnimationFrame = undefined,
wrapper = undefined,
callback = undefined,
geckoVersion = 0,
userAgent = navigator.userAgent,
index = 0,
self = this;
// Workaround for Chrome 10 bug where Chrome
// does not pass the time to the animation function
if (window.webkitRequestAnimationFrame) {
// Define the wrapper
wrapper = function (time) {
if (time === undefined) {
time = +new Date();
}
self.callback(time);
};
// Make the switch
originalWebkitRequestAnimationFrame = window.webkitRequestAnimationFrame;
window.webkitRequestAnimationFrame = function (callback, element) {
self.callback = callback;
// Browser calls the wrapper and wrapper calls the callback
originalWebkitRequestAnimationFrame(wrapper, element);
}
}
// Workaround for Gecko 2.0, which has a bug in
// mozRequestAnimationFrame() that restricts animations
// to 30-40 fps.
if (window.mozRequestAnimationFrame) {
// Check the Gecko version. Gecko is used by browsers
// other than Firefox. Gecko 2.0 corresponds to
// Firefox 4.0.
index = userAgent.indexOf('rv:');
if (userAgent.indexOf('Gecko') != -1) {
geckoVersion = userAgent.substr(index + 3, 3);
if (geckoVersion === '2.0') {
// Forces the return statement to fall through
// to the setTimeout() function.
window.mozRequestAnimationFrame = undefined;
}
}
}
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback, element) {
var start,
finish;
window.setTimeout( function () {
start = +new Date();
callback(start);
finish = +new Date();
self.timeout = 1000 / 60 - (finish - start);
}, self.timeout);
};
}
)
();
// It's then used here in our code here:
loadIcons();
function loadIcons() {
var elements = document.querySelectorAll('img');
if (!elements) return;
Array.prototype.forEach.call(elements, function(el, i){
var watcher = scrollMonitor.create(el, 2000);
watcher.enterViewport(function() {
var srcToInject = el.getAttribute('data-src');
var src = el.getAttribute('src');
if (src === null && srcToInject!=null) { // do not re-execute for images already with injected src
el.style.opacity = 0;
el.style.display = "block";
el.setAttribute('src',srcToInject);
el.onload = imageFound;
el.onerror = imageNotFound;
function imageFound() {
// progressively show image via opacity variation
(function fade() {
var val = parseFloat(el.style.opacity);
if (!((val += .1) > 1)) {
el.style.opacity = val;
requestNextAnimationFrame(fade);
}
})();
}
}
});
});
}
then we do in main.js
import {requestNextAnimationFrame} from './helpers/requestAnimationFramePolyfill.js'
loadIcons();
function loadCompanyIcons() {
var elements = document.querySelectorAll('img');
if (!elements) return;
Array.prototype.forEach.call(elements, function(el, i){
var watcher = scrollMonitor.create(el, 2000);
watcher.enterViewport(function() {
var srcToInject = el.getAttribute('data-src');
var src = el.getAttribute('src');
if (src === null && srcToInject!=null) { // do not re-execute for images already with injected src
el.style.opacity = 0;
el.style.display = "block";
el.setAttribute('src',srcToInject);
el.onload = imageFound;
el.onerror = imageNotFound;
function imageFound() {
// progressively show image via opacity variation
(function fade() {
var val = parseFloat(el.style.opacity);
if (!((val += .1) > 1)) {
el.style.opacity = val;
requestNextAnimationFrame(fade);
}
})();
}
}
});
});
}
We also tried:
import {window.requestNextAnimationFrame} from './helpers/requestAnimationFramePolyfill.js'
but none work and we know this because the icons supposed to use requestAnimationFramePolyfill.js to progressively fade iunto a 1.0 opacity, remain with 0.1 opacity.
I'm not sure though this is the reason. I could not understand it for the past day.
You are trying to add a function in to window object then use it in other place. It's one way to make a function access able by other files, but with ES6 and webpack you can do it other way.
I suggest to not use variable window because its may cause some issue with window syntax. Also you do not need to add a function to window object anymore.
This should work for you.
js/helpers/requestAnimationFramePolyfill.js
const requestNextAnimationFrame = (function { your function });
export { requestNextAnimationFrame };
main.js
import { requestNextAnimationFrame } from './helpers/requestAnimationFramePolyfill.js'
Related
This is my code
document.addEventListener('scroll', function (e) {
var outer1 = document.getElementById('outer1');
var outer2 = document.getElementById('outer2');
-------
--------
}
I am using jQuery version jQuery v1.11.0 . But I got this error. Currently there are many similar usages and this issue is only visible on IE8
Compatibility
You can work around the addEventListener, removeEventListener,
Event.preventDefault and Event.stopPropagation not being supported by
IE 8 using the following code at the beginning of your script. The
code supports the use of handleEvent and also the DOMContentLoaded
event.
Note: useCapture is not supported, as IE 8 does not have any
alternative method of it. Please also note that the following code
only adds support to IE 8.
(function() {
if (!Event.prototype.preventDefault) {
Event.prototype.preventDefault=function() {
this.returnValue=false;
};
}
if (!Event.prototype.stopPropagation) {
Event.prototype.stopPropagation=function() {
this.cancelBubble=true;
};
}
if (!Element.prototype.addEventListener) {
var eventListeners=[];
var addEventListener=function(type,listener /*, useCapture (will be ignored) */) {
var self=this;
var wrapper=function(e) {
e.target=e.srcElement;
e.currentTarget=self;
if (listener.handleEvent) {
listener.handleEvent(e);
} else {
listener.call(self,e);
}
};
if (type=="DOMContentLoaded") {
var wrapper2=function(e) {
if (document.readyState=="complete") {
wrapper(e);
}
};
document.attachEvent("onreadystatechange",wrapper2);
eventListeners.push({object:this,type:type,listener:listener,wrapper:wrapper2});
if (document.readyState=="complete") {
var e=new Event();
e.srcElement=window;
wrapper2(e);
}
} else {
this.attachEvent("on"+type,wrapper);
eventListeners.push({object:this,type:type,listener:listener,wrapper:wrapper});
}
};
var removeEventListener=function(type,listener /*, useCapture (will be ignored) */) {
var counter=0;
while (counter<eventListeners.length) {
var eventListener=eventListeners[counter];
if (eventListener.object==this && eventListener.type==type && eventListener.listener==listener) {
if (type=="DOMContentLoaded") {
this.detachEvent("onreadystatechange",eventListener.wrapper);
} else {
this.detachEvent("on"+type,eventListener.wrapper);
}
break;
}
++counter;
}
};
Element.prototype.addEventListener=addEventListener;
Element.prototype.removeEventListener=removeEventListener;
if (HTMLDocument) {
HTMLDocument.prototype.addEventListener=addEventListener;
HTMLDocument.prototype.removeEventListener=removeEventListener;
}
if (Window) {
Window.prototype.addEventListener=addEventListener;
Window.prototype.removeEventListener=removeEventListener;
}
}
})();
Internet Explorer (up to version 8) used an alternate attachEvent method.
you can try this for cross-browser addEvent function.
function addEvent(evnt, elem, func) {
if (elem.addEventListener) // W3C DOM
elem.addEventListener(evnt,func,false);
else if (elem.attachEvent) { // IE DOM
elem.attachEvent("on"+evnt, func);
}
else { // No much to do
elem[evnt] = func;
}
}
In-case anyone needs IE7 support, try the below, it worked for me, thanks all for the scripts above.
function preloadImages(array, waitForOtherResources, timeout) {
var loaded = false, list = preloadImages.list, imgs = array.slice(0), t = timeout || 15 * 1000, timer;
if (!preloadImages.list) {
preloadImages.list = [];
}
if (!waitForOtherResources || document.readyState === 'complete') {
loadNow();
} else {
addEvent('load', window, function () {
clearTimeout(timer);
loadNow();
});
// in case window.addEventListener doesn't get called (sometimes some resource gets stuck)
// then preload the images anyway after some timeout time
timer = setTimeout(loadNow, t);
}
function addEvent(evnt, elem, func) {
if (elem.addEventListener) // W3C DOM
elem.addEventListener(evnt, func, false);
else if (elem.attachEvent) { // IE DOM
elem.attachEvent("on" + evnt, func);
}
else { // No much to do
elem[evnt] = func;
}
}
function loadNow() {
if (!loaded) {
loaded = true;
for (var i = 0; i < imgs.length; i++) {
var img = new Image();
img.onload = img.onerror = img.onabort = function () {
var index = preloadImages.list.indexOf(this);
if (index !== -1) {
// remove image from the array once it's loaded
// for memory consumption reasons
preloadImages.list.splice(index, 1);
}
}
preloadImages.list.push(img);
img.src = imgs[i];
}
}
}
}
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement, fromIndex) {
var k;
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
var O = Object(this);
var len = O.length >>> 0;
if (len === 0) {
return -1;
}
var n = +fromIndex || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
if (n >= len) {
return -1;
}
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
while (k < len) {
if (k in O && O[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
}
I know very little about Javascript but need to use hammer.js in a project I'm working on.
Instead of replacing/refreshing the image im trying to use the pull to refresh scrit to refresh the page.
Ive tried adding
location.reload();
to the script but to no avail, can anyone shed any light on this.
http://eightmedia.github.io/hammer.js/
This is the code im using
/**
* requestAnimationFrame and cancel polyfill
*/
(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame =
window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}());
/**
* pull to refresh
* #type {*}
*/
var PullToRefresh = (function() {
function Main(container, slidebox, slidebox_icon, handler) {
var self = this;
this.breakpoint = 80;
this.container = container;
this.slidebox = slidebox;
this.slidebox_icon = slidebox_icon;
this.handler = handler;
this._slidedown_height = 0;
this._anim = null;
this._dragged_down = false;
this.hammertime = Hammer(this.container)
.on("touch dragdown release", function(ev) {
self.handleHammer(ev);
});
};
/**
* Handle HammerJS callback
* #param ev
*/
Main.prototype.handleHammer = function(ev) {
var self = this;
switch(ev.type) {
// reset element on start
case 'touch':
this.hide();
break;
// on release we check how far we dragged
case 'release':
if(!this._dragged_down) {
return;
}
// cancel animation
cancelAnimationFrame(this._anim);
// over the breakpoint, trigger the callback
if(ev.gesture.deltaY >= this.breakpoint) {
container_el.className = 'pullrefresh-loading';
pullrefresh_icon_el.className = 'icon loading';
this.setHeight(60);
this.handler.call(this);
}
// just hide it
else {
pullrefresh_el.className = 'slideup';
container_el.className = 'pullrefresh-slideup';
this.hide();
}
break;
// when we dragdown
case 'dragdown':
this._dragged_down = true;
// if we are not at the top move down
var scrollY = window.scrollY;
if(scrollY > 5) {
return;
} else if(scrollY !== 0) {
window.scrollTo(0,0);
}
// no requestAnimationFrame instance is running, start one
if(!this._anim) {
this.updateHeight();
}
// stop browser scrolling
ev.gesture.preventDefault();
// update slidedown height
// it will be updated when requestAnimationFrame is called
this._slidedown_height = ev.gesture.deltaY * 0.4;
break;
}
};
/**
* when we set the height, we just change the container y
* #param {Number} height
*/
Main.prototype.setHeight = function(height) {
if(Modernizr.csstransforms3d) {
this.container.style.transform = 'translate3d(0,'+height+'px,0) ';
this.container.style.oTransform = 'translate3d(0,'+height+'px,0)';
this.container.style.msTransform = 'translate3d(0,'+height+'px,0)';
this.container.style.mozTransform = 'translate3d(0,'+height+'px,0)';
this.container.style.webkitTransform = 'translate3d(0,'+height+'px,0) scale3d(1,1,1)';
}
else if(Modernizr.csstransforms) {
this.container.style.transform = 'translate(0,'+height+'px) ';
this.container.style.oTransform = 'translate(0,'+height+'px)';
this.container.style.msTransform = 'translate(0,'+height+'px)';
this.container.style.mozTransform = 'translate(0,'+height+'px)';
this.container.style.webkitTransform = 'translate(0,'+height+'px)';
}
else {
this.container.style.top = height+"px";
}
};
/**
* hide the pullrefresh message and reset the vars
*/
Main.prototype.hide = function() {
container_el.className = '';
this._slidedown_height = 0;
this.setHeight(0);
cancelAnimationFrame(this._anim);
this._anim = null;
this._dragged_down = false;
};
/**
* hide the pullrefresh message and reset the vars
*/
Main.prototype.slideUp = function() {
var self = this;
cancelAnimationFrame(this._anim);
pullrefresh_el.className = 'slideup';
container_el.className = 'pullrefresh-slideup';
this.setHeight(0);
setTimeout(function() {
self.hide();
}, 500);
};
/**
* update the height of the slidedown message
*/
Main.prototype.updateHeight = function() {
var self = this;
this.setHeight(this._slidedown_height);
if(this._slidedown_height >= this.breakpoint){
this.slidebox.className = 'breakpoint';
this.slidebox_icon.className = 'icon arrow arrow-up';
}
else {
this.slidebox.className = '';
this.slidebox_icon.className = 'icon arrow';
}
this._anim = requestAnimationFrame(function() {
self.updateHeight();
});
};
return Main;
})();
function getEl(id) {
return document.getElementById(id);
}
var container_el = getEl('container');
var pullrefresh_el = getEl('pullrefresh');
var pullrefresh_icon_el = getEl('pullrefresh-icon');
var image_el = getEl('random-image');
var refresh = new PullToRefresh(container_el, pullrefresh_el, pullrefresh_icon_el);
// update image onrefresh
refresh.handler = function() {
var self = this;
// a small timeout to demo the loading state
setTimeout(function() {
var preload = new Image();
preload.onload = function() {
image_el.src = this.src;
self.slideUp();
};
preload.src = 'http://lorempixel.com/800/600/?'+ (new Date().getTime());
}, 1000);
};
There is a Beer involved for anyone that can fix this :)
http://jsfiddle.net/zegermens/PDcr9/1/
You're assigning the return value of the location.reload function to the src attribute of an Image element. I'm not sure if the function even has a return value, https://developer.mozilla.org/en-US/docs/Web/API/Location.reload
Try this:
// update image onrefresh
refresh.handler = function() {
var self = this;
// a small timeout to demo the loading state
setTimeout(function() {
window.location.reload();
}, 1000);
};
I moved from using setTimeout to requestAnimationFrame as per the post at:
http://paulirish.com/2011/requestanimationframe-for-smart-animating/
How I can set some code inside my animation() loop to only execute every second?
I currently do something like:
animate() {
if(playGame) {
requestAnimFrame(animate);
}
var time = new Date().getTime();
if(time % 1000 <= 10) {
// code to run ~every second
}
// Also need to fix this, as it executes too fast, need to add score only
// every 100 milliseconds (player must stay in zone for 2 seconds to win)
if(playerInZone()) {
gameScore++;
if(gameScore >= 100) {
endGame();
}
} else {
gameScore = 0;
}
}
I'm not sure if calling the time like that and performing modulus is the right way? Also in what way would I change my gameScore code to only fire every (for example) 200 milliseconds?
NOTE:
I use this code at the top of my JavaScript file:
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(/* function */ callback, /* DOMElement */ element){
window.setTimeout(callback, 1000 / 60);
};
})();
But I've also included rAF.js in my file, however unsure which to use:
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
// http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
// requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel
// MIT license
(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}());
When requestAnimationFrame is called the "current time" is sent in milliseconds, so you could do something like this:
var lastTime = 0;
animate(currentTime) {
if (currentTime >= lastTime + 1000) {
// one second has passed, run some code here
lastTime = currentTime;
}
if(playGame) {
requestAnimationFrame(animate);
}
}
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
welcome all ,
i have a problem with my images slider , it runs successfuly until poll script excuted then it stops , tried to combine both scripts didn't work also tried to use noConflict but in stops both of them .
this is the slider
(function ($) {
$.fn.s3Slider = function (vars) {
var element = this;
var timeOut = (vars.timeOut != undefined) ? vars.timeOut : 4000;
var current = null;
var timeOutFn = null;
var faderStat = true;
var mOver = false;
var items = $("#sliderContent .sliderImage");
var itemsSpan = $("#sliderContent .sliderImage span");
items.each(function (i) {
$(items[i]).mouseover(function () {
mOver = true
});
$(items[i]).mouseout(function () {
mOver = false;
fadeElement(true)
})
});
var fadeElement = function (isMouseOut) {
var thisTimeOut = (isMouseOut) ? (timeOut / 2) : timeOut;
thisTimeOut = (faderStat) ? 10 : thisTimeOut;
if (items.length > 0) {
timeOutFn = setTimeout(makeSlider, thisTimeOut)
} else {
console.log("Poof..")
}
};
var makeSlider = function () {
current = (current != null) ? current : items[(items.length - 1)];
var currNo = jQuery.inArray(current, items) + 1;
currNo = (currNo == items.length) ? 0 : (currNo - 1);
var newMargin = $(element).width() * currNo;
if (faderStat == true) {
if (!mOver) {
$(items[currNo]).fadeIn((timeOut / 6), function () {
if ($(itemsSpan[currNo]).css("bottom") == 0) {
$(itemsSpan[currNo]).slideUp((timeOut / 6), function () {
faderStat = false;
current = items[currNo];
if (!mOver) {
fadeElement(false)
}
})
} else {
$(itemsSpan[currNo]).slideDown((timeOut / 6), function () {
faderStat = false;
current = items[currNo];
if (!mOver) {
fadeElement(false)
}
})
}
})
}
} else {
if (!mOver) {
if ($(itemsSpan[currNo]).css("bottom") == 0) {
$(itemsSpan[currNo]).slideDown((timeOut / 6), function () {
$(items[currNo]).fadeOut((timeOut / 6), function () {
faderStat = true;
current = items[(currNo + 1)];
if (!mOver) {
fadeElement(false)
}
})
})
} else {
$(itemsSpan[currNo]).slideUp((timeOut / 6), function () {
$(items[currNo]).fadeOut((timeOut / 6), function () {
faderStat = true;
current = items[(currNo + 1)];
if (!mOver) {
fadeElement(false)
}
})
})
}
}
}
};
makeSlider()
}
})(jQuery);
and this is the poll script
window.onload = function() {
$(".sidePollCon").load("ar_poll.html", function(r, s, xhr) {
if (s == "error") {
$(".sidePollCon").load("poll.html");
} else {
$(".vote_booroo").html("صوت الان");
$(".viewresults").html("شاهد النتيجة");
$("fieldset p").html("");
$(".results_booroo p").html("");
$(".result_booroo").attr("src", "../images/poll_color.jpg");
}
});
};
One potential problem could be the window.onload assignment. It is very prone to conflict.
Every time you do window.onload = the previous assignemnt will be overridden. See demo here:
The output shows that the first window.onload assignment never gets called, while the jQuery alternative does get called.
jQuery.noConflict does little in this regard. All it does is to prevent override the $ symbol so that another lib can use it.
So if you are also using the window.onload event to invoke the slider, then you have conflict. You can easily solve this problem by using the jquery format:
$(window).load(function() {
...
});
However usually you would tie the event to $(document).load(function(){...}); or in short form: $(function(){...}).
So for your poll that would be:
$(function(){
$(".sidePollCon").load("ar_poll.html", function(r, s, xhr) {
if (s == "error") {
$(".sidePollCon").load("poll.html");
} else {
$(".vote_booroo").html("صوت الان");
$(".viewresults").html("شاهد النتيجة");
$("fieldset p").html("");
$(".results_booroo p").html("");
$(".result_booroo").attr("src", "../images/poll_color.jpg");
}
});
});
Hope that helps.
resolving conflicts in jquery (possibly with another JS library .. like script.aculo.us) can be resolved using noconflict()
http://api.jquery.com/jQuery.noConflict/
$.noConflict();
but make sure that u have no error in your javascript code itself. use firebug and
console.log('') to test your script.