jQuery: how to implement controller for slider (carousel)? - javascript

I have build a slider using jQuery which works fine. It was a quick development so that didn't get time to add controller. Right now it is getting hard to fix controller for the carousel.
Does any one have solution or alternative to fix this?
Demo http://jsfiddle.net/sweetmaanu/Pn2UB/16/
$.fx.speeds._default = 1000;
function slider(container) {
var currPg = null,
firstPg = null;
container.find('> .pg').each(function (idx, pg) {
pg = $(pg);
var o = {
testimonial: pg.find('> .testimonial'),
thumb: pg.find('> .testimonial-thumb'),
pg: pg
};
o.pg.css({
position: 'absolute',
width: '100%',
height: '100%',
});
if (idx > 0) {
o.pg.css({
opacity: 0,
'z-index': -1
});
o.testimonial.css({
'margin-left': '100%'
});
o.thumb.css({
'bottom': '-100%'
});
} else {
firstPg = o;
}
o.prev = currPg;
if (currPg) {
currPg.next = o;
}
currPg = o;
});
firstPg.prev = currPg;
currPg.next = firstPg;
currPg = firstPg;
this.advance = function advance(duration) {
console.log("advance!", this);
var dur = duration || $.fx.speeds._default;
var dur2 = Math.ceil(dur / 2);
var dh = container.height();
var dw = container.width();
var nextPg = currPg.next;
nextPg.pg.css({
opacity: 1,
'z-index': null
});
var _pg = currPg;
currPg.testimonial.stop().animate({
'margin-left': -dw
}, dur, function () {
_pg.pg.css({
opacity: 0,
'z-index': -1
});
_pg = null;
});
nextPg.testimonial.stop()
.css({
'margin-left': dw
})
.animate({
'margin-left': 0
}, dur);
currPg.thumb.stop().animate({
'bottom': -dh
}, dur2, function () {
nextPg.thumb.stop()
.css({
'bottom': -dh
})
.animate({
'bottom': 0
}, dur2);
nextPg = null;
});
currPg = nextPg;
}
}
var s = new slider($('#banner'));
function scheduleNext() {
setTimeout(function () {
s.advance();
scheduleNext();
}, 5000);
}
scheduleNext();

You just want to add a variable direction and change that on click of both prev and next
var direction = 'left';
$('#next').click(function(event) {
direction = 'right';
s.advance(1000,direction);
});
$('#prev').click(function(event) {
direction = 'left';
s.advance(1000,direction);
});
then add a line where it checks the direction variable
if(direction == 'left')
var dw = container.width();
else if(direction =='right')
var dw = - container.width();
else{
console.log('Wrong direction')
return;
}
Carosal fixed
Don't forget to add argument on advanced function

For next slider you need:
$('#next').click(function(){
s.advance();
});
But anyway you have to construct universal animations methods with parameters.
Check this examples:
http://jsfiddle.net/lalatino/pjTU2/
and
http://sorgalla.com/projects/jcarousel/examples/static_controls.html

Related

Adding a SetInterval function in jquery

So I have this code from here: j360
This code is perfect for what I want: an html wich has a draggable 360º product image view, but it lacks one thing: a button for auto rotation.
I already have the button into the html, but I can't, for more that I try, to make a function or anything to make the images go by itself, and not only when I drag it over the screen.
Here is the code I have in the moment.
(function($){
$.fn.j360 = function(options) {
var defaults = {
clicked: false,
currImg: 1
}
var options = jQuery.extend(defaults, options);
return this.each(function() {
var $obj = jQuery(this);
var aImages = {};
$obj.css({
'margin-left' : 'auto',
'margin-right' : 'auto',
'text-align' : 'center',
'overflow' : 'hide'
});
$overlay = $obj.clone(true);
$overlay.html('<img src="images/loader.gif" class="loader" style="margin-top:' + ($obj.height()/2 - 15) + 'px" />');
$overlay.attr('id', 'view_overlay');
$overlay.css({
'position' : 'absolute',
'z-index': '5',
'top' : $obj.offset().top,
'left' : $obj.offset().left,
'background' : '#fff'
});
$obj.after($overlay);
$obj.after('<div id="colors_ctrls"></div>');
jQuery('#colors_ctrls').css({
'width' : $obj.width(),
'position' : 'absolute',
'z-index': '5',
'top' : $obj.offset().top + $obj.height - 50,
'left' : $obj.offset().left
});
var imageTotal = 0;
jQuery('img', $obj).each(function() {
aImages[++imageTotal] = jQuery(this).attr('src');
preload(jQuery(this).attr('src'));
})
var imageCount = 0;
jQuery('.preload_img').load(function() {
if (++imageCount == imageTotal) {
$overlay.animate({
'filter' : 'alpha(Opacity=0)',
'opacity' : 0
}, 100);
$obj.html('<img src="' + aImages[1] + '" />');
$overlay.bind('mousedown touchstart', function(e) {
if (e.type == "touchstart") {
options.currPos = window.event.touches[0].pageX;
} else {
options.currPos = e.pageX;
}
options.clicked = true;
return false;
});
jQuery(document).bind('mouseup touchend', function() {
options.clicked = false;
});
jQuery(document).bind('mousemove touchmove', function(e) {
if (options.clicked) {
var pageX;
if (e.type == "touchmove") {
pageX = window.event.targetTouches[0].pageX;
} else {
pageX = e.pageX;
}
var width_step = 50;
if (Math.abs(options.currPos - pageX) >= width_step) {
if (options.currPos - pageX >= width_step) {
options.currImg++;
if (options.currImg > imageTotal) {
options.currImg = 1;
}
} else {
options.currImg--;
if (options.currImg < 1) {
options.currImg = imageTotal;
}
}
options.currPos = pageX;
$obj.html('<img src="' + aImages[options.currImg] + '" />');
}
}
});
}
});
if (jQuery.browser.msie || jQuery.browser.mozilla || jQuery.browser.opera || jQuery.browser.safari ) {
jQuery(window).resize(function() {
onresizeFunc($obj, $overlay);
});
} else {
var supportsOrientationChange = "onorientationchange" in window,
orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";
window.addEventListener(orientationEvent, function() {
onresizeFunc($obj, $overlay);
}, false);
}
onresizeFunc($obj, $overlay)
});
}
})
(jQuery)
function onresizeFunc($obj, $overlay){
$obj.css({
'margin-top' : $(document).height()/2
});
$overlay.css({
'margin-top' : 200,
'top' : $obj.offset().top,
'left' : $obj.offset().left
});
jQuery('#colors_ctrls').css({
'top' : $obj.offset().top + $obj.height - 50,
'left' : $obj.offset().left
})
}
function preload(image) {
if (typeof document.body == "undefined") return;
try {
var div = document.createElement("div");
var s = div.style;
s.position = "absolute";
s.top = s.left = 0;
s.visibility = "hidden";
document.body.appendChild(div);
div.innerHTML = "<img class=\"preload_img\" src=\"" + image + "\" />";
}
catch(e) {
// Error. Do nothing.
}
};
I need a method to increment over time a function, to make the ilusion of auto-rotate.
This plugin doesn’t seem to have this option (a kind of autoplay) so you have to code it or search an other plugin.
Since it is a list of image, you can maybe don’t use the plugin and display images one after another with jQuery and .delay()

JS carrousel stop when mouse over

I run a real estate site and I have a property carrousel, I would like to modify this JS in order to stop the carrousel when user over with mouse.
Code:
var Ticker = new Class({
setOptions: function (options) {
this.options = Object.extend({
speed: 5000,
delay: 5000,
direction: 'vertical',
onComplete: Class.empty,
onStart: Class.empty
}, options || {});
},
initialize: function (el, options) {
this.setOptions(options);
this.el = $(el);
this.items = this.el.getElements('li');
var w = 0;
var h = 0;
if (this.options.direction.toLowerCase() == 'horizontal') {
h = this.el.getSize().size.y;
this.items.each(function (li, index) {
w += li.getSize().size.x;
});
} else {
w = this.el.getSize().size.x;
this.items.each(function (li, index) {
h += li.getSize().size.y;
});
}
this.el.setStyles({
position: 'absolute',
top: 0,
left: 0,
width: w,
height: h
});
this.fx = new Fx.Styles(this.el, {
duration: this.options.speed,
onComplete: function () {
var i = (this.current == 0) ? this.items.length : this.current;
this.items[i - 1].injectInside(this.el);
this.el.setStyles({
left: 0,
top: 0
});
}.bind(this)
});
this.current = 0;
this.next();
},
next: function () {
this.current++;
if (this.current >= this.items.length) this.current = 0;
var pos = this.items[this.current];
this.fx.start({
top: -pos.offsetTop,
left: -pos.offsetLeft
});
this.next.bind(this).delay(this.options.delay + this.options.speed);
}
});
var hor = new Ticker('TickerVertical', {
speed: 1000,
delay: 4000,
direction: 'horizontal'
});
This version of mootools is really really old (1.1 isn't it? ) So the solution is something like this (not tested):
var Ticker = new Class({
setOptions: function (options) {
this.options = Object.extend({
speed: 5000,
delay: 5000,
direction: 'vertical',
onComplete: Class.empty,
onStart: Class.empty
}, options || {});
},
initialize: function (el, options) {
this.setOptions(options);
this.el = $(el);
//set a flag according to the mouse in/out events:
var self = this;
this.el.addEvents({
'mouseenter': function(){
self.elementHover = true;
},
'mouseleave': function(){
self.elementHover = false;
}
})
this.items = this.el.getElements('li');
var w = 0;
var h = 0;
if (this.options.direction.toLowerCase() == 'horizontal') {
h = this.el.getSize().size.y;
this.items.each(function (li, index) {
w += li.getSize().size.x;
});
} else {
w = this.el.getSize().size.x;
this.items.each(function (li, index) {
h += li.getSize().size.y;
});
}
this.el.setStyles({
position: 'absolute',
top: 0,
left: 0,
width: w,
height: h
});
this.fx = new Fx.Styles(this.el, {
duration: this.options.speed,
onComplete: function () {
var i = (this.current == 0) ? this.items.length : this.current;
this.items[i - 1].injectInside(this.el);
this.el.setStyles({
left: 0,
top: 0
});
}.bind(this)
});
this.current = 0;
this.next();
},
next: function () {
if(!this.elementHover){ //check here the flag mouse in/out
this.current++;
if (this.current >= this.items.length) this.current = 0;
var pos = this.items[this.current];
this.fx.start({
top: -pos.offsetTop,
left: -pos.offsetLeft
});
}
this.next.bind(this).delay(this.options.delay + this.options.speed);
}
});

javascript slideshow pauseonhover

my question is really simple and something can help a lot of people out there,
I want my slideshow to NOT stop when someone hover over it,
I was able to do it for one of my sites, by accessing the .js (nivooSlider.js) and adding to the list of options: the "false" value to the pauseOnHover option (pauseOnHover: false,)
and that did it! ...
Now I'm also trying to get the same result in another of my websites that is currently using rokSlider, which does not have that option by default, so i'm wondering, if i go to the options list and simple add this options+value ... Do you think that will work?
Regards
var Slideshow = new Class({
version: '3.0.3',
options: {
captions: true,
showTitleCaption: true,
classes: ['prev', 'next', 'active'],
duration: [2000, 4000],
path: '/',
navigation: false,
pan: 100,
resize: true,
thumbnailre: [/\./, 't.'],
transition: Fx.Transitions.Sine.easeInOut,
type: 'fade',
zoom: 50,
loadingDiv: true,
removeDiv: true
},
styles: {
caps: {
div: {
opacity: 0,
position: 'absolute',
width: '100%',
margin: 0,
left: 0,
bottom: 0,
height: 40,
background: '#333',
color: '#fff',
textIndent: 0
},
h2: {
color: 'red',
padding: 0,
fontSize: '80%',
margin: 0,
margin: '2px 5px',
fontWeight: 'bold'
},
p: {
padding: 0,
fontSize: '60%',
margin: '2px 5px',
color: '#eee'
}
}
},
initialize: function(el, options) {
this.setOptions($merge({
onClick: this.onClick.bind(this)
}, options));
if(!this.options.images) return;
this.options.pan = this.mask(this.options.pan);
this.options.zoom = this.mask(this.options.zoom);
this.el = $(el).empty();
this.caps = {
div: new Element('div', {
styles: this.styles.caps.div,
'class': 'captionDiv'
}),
h2: new Element('h2', {
styles: this.styles.caps.h2,
'class': 'captionTitle'
}),
p: new Element('p', {
styles: this.styles.caps.p,
'class': 'captionDescription'
})
};
this.fx = [];
var trash = new ImageLoader(this.el, this.options.images, {
loadingDiv: this.options.loadingDiv,
onComplete: this.start.bind(this),
path: this.options.path,
removeDiv: this.options.removeDiv
});
},
start: function() {
this.imgs = $A(arguments);
this.a = this.imgs[0].clone().set({
styles: {
display: 'block',
position: 'absolute',
left: 0,
'top': 0,
zIndex: 1
}
}).injectInside(this.el);
var obj = this.a.getCoordinates();
this.height = this.options.height || obj.height;
this.width = this.options.width || obj.width;
this.el.setStyles({
display: 'block',
position: 'relative',
width: this.width
});
this.el.empty();
this.el.adopt((new Element('div', {
events: {
'click': this.onClick.bind(this)
},
styles: {
display: 'block',
overflow: 'hidden',
position: 'relative',
width: this.width,
height: this.height
}
})).adopt(this.a));
this.resize(this.a, obj);
this.b = this.a.clone().setStyle('opacity', 0).injectAfter(this.a);
this.timer = [0, 0];
this.navigation();
this.direction = 'left';
this.curr = [0,0];
$(document.body).adopt(new Element('div', {
id: 'hiddenDIV',
styles: {
visibility: 'hidden',
height: 0,
width: 0,
overflow: 'hidden',
opacity: 0
}
}));
this.loader = this.imgs[0];
$('hiddenDIV').adopt(this.loader);
this.load();
},
load: function(fast) {
if ($time() > this.timer[0]) {
this.img = (this.curr[1] % 2) ? this.b : this.a;
this.img.setStyles({
opacity: 0,
width: 'auto',
height: 'auto',
zIndex: this.curr[1]
});
var url = this.options.images[this.curr[0]].url;
this.img.setStyle('cursor', (url != '#' && url != '') ? 'pointer' : 'default');
this.img.setProperties({
src: this.loader.src,
title: this.loader.title,
alt: this.loader.alt
});
this.resize(this.img, this.loader);
if(fast){
this.img.setStyles({
top: 0,
left: 0,
opacity: 1
});
this.captions();
this.loaded();
return;
}
this.captions();
this[this.options.type.test(/push|wipe/) ? 'swipe' : 'kens']();
this.loaded();
} else {
this.timeout = this.load.delay(100, this);
}
},
loaded: function() {
if(this.ul) {
this.ul.getElements('a[name]').each(function(a, i) {
a[(i === this.curr[0] ? 'add' : 'remove') + 'Class'](this.options.classes[2]);
}, this);
}
this.direction = 'left';
this.curr[0] = (this.curr[0] + 1) % this.imgs.length;
this.curr[1]++;
this.timer[0] = $time() + this.options.duration[1] + (this.options.type.test(/fade|push|wipe/) ? this.options.duration[0] : 0);
this.timer[1] = $time() + this.options.duration[0];
this.loader = this.imgs[this.curr[0]];
$('hiddenDIV').empty().adopt(this.loader);
this.load();
},
kens: function() {
this.img.setStyles({
bottom: 'auto',
right: 'auto',
left: 'auto',
top: 'auto'
});
var arr = ['left top', 'right top', 'left bottom', 'right bottom'].getRandom().split(' ');
arr.each(function(p) {
this.img.setStyle(p, 0);
}, this);
var zoom = this.options.type.test(/zoom|combo/) ? this.zoom() : {};
var pan = this.options.type.test(/pan|combo/) ? this.pan(arr) : {};
this.fx.push(this.img.effect('opacity', {duration: this.options.duration[0]}).start(1));
this.fx.push(this.img.effects({duration: this.options.duration[0] + this.options.duration[1]}).start($merge(zoom, pan)));
},
zoom: function() {
var n = Math.max(this.width / this.loader.width, this.height / this.loader.height);
var z = (this.options.zoom === 'rand') ? Math.random() + 1 : (this.options.zoom.toInt() / 100.0) + 1;
var eh = Math.ceil(this.loader.height * n);
var ew = Math.ceil(this.loader.width * n);
var sh = (eh * z).toInt();
var sw = (ew * z).toInt();
return {height: [sh, eh], width: [sw, ew]};
},
pan: function(arr) {
var ex = this.width - this.img.width, ey = this.height - this.img.height;
var p = this.options.pan === 'rand' ? Math.random() : Math.abs((this.options.pan.toInt() / 100) - 1);
var sx = (ex * p).toInt(), sy = (ey * p).toInt();
var x = this.width / this.loader.width > this.height / this.loader.height;
var obj = {};
obj[arr[x ? 1 : 0]] = x ? [sy, ey] : [sx, ex];
return obj;
},
swipe: function() {
var arr, p0 = {}, p1 = {}, x;
this.img.setStyles({
left: 'auto',
right: 'auto',
opacity: 1
}).setStyle(this.direction, this.width);
if(this.options.type === 'wipe') {
this.fx.push(this.img.effect(this.direction, {
duration: this.options.duration[0],
transition: this.options.transition
}).start(0));
} else {
arr = [this.img, this.curr[1] % 2 ? this.a : this.b];
p0[this.direction] = [this.width, 0];
p1[this.direction] = [0, -this.width];
if(arr[1].getStyle(this.direction) === 'auto') {
x = this.width - arr[1].getStyle('width').toInt();
arr[1].setStyle(this.direction, x);
arr[1].setStyle(this.direction === 'left' ? 'right' : 'left', 'auto');
p1[this.direction][0] = x;
}
this.fx.push(new Fx.Elements(arr, {
duration: this.options.duration[0],
transition: this.options.transition
}).start({
'0': p0,
'1': p1
}));
}
},
captions: function(img) {
img = img || this.img;
if(!this.options.captions || (!img.title && !img.alt)) return;
this.el.getFirst().adopt(this.caps.div.adopt(this.caps.h2, this.caps.p));
(function () {
if (this.options.showTitleCaption) this.caps.h2.setHTML(img.title);
this.caps.p.setHTML(img.alt);
this.caps.div.setStyle('zIndex', img.getStyle('zIndex')*2 || 10);
this.capsHeight = this.capsHeight || this.options.captionHeight || this.caps.div.offsetHeight;
var fx = this.caps.div.effects().set({'height': 0}).start({
opacity: 0.7,
height: this.capsHeight
});
(function(){
fx.start({
opacity: 0,
height: 0
});
}).delay(1.00*(this.options.duration[1] - this.options.duration[0]));
}).delay(0.75*(this.options.duration[0]), this);
},
navigation: function() {
if(!this.options.navigation) return;
var i, j, atemp;
var fast = this.options.navigation.test(/fast/) ;
this.ul = new Element('ul');
var li = new Element('li'), a = new Element('a');
if (this.options.navigation.test(/arrows/)) {
this.ul.adopt(li.clone()
.adopt(a.clone()
.addClass(this.options.classes[0])
.addEvent('click', function() {
if (fast || $time() > this.timer[1]) {
$clear(this.timeout);
// Clear the FX array only for fast navigation since this stops combo effects
if(fast) {
this.fx.each(function(fx) {
fx.time = 0;
fx.options.duration = 0;
fx.stop(true);
});
}
this.direction = 'right';
this.curr[0] = (this.curr[0] < 2) ? this.imgs.length - (2 - this.curr[0]) : this.curr[0] - 2;
this.timer = [0];
this.loader = this.imgs[this.curr[0]];
this.load(fast);
}
}.bind(this))
)
);
}
if (this.options.navigation.test(/arrows\+|thumbnails/)) {
for (i = 0, j = this.imgs.length; i < j; i++) {
atemp = a.clone().setProperty('name', i);
if (this.options.navigation.test(/thumbnails/)) atemp.setStyle('background-image', 'url(' + this.imgs[i].src + ')');
if(i === 0) a.className = this.options.classes[2];
atemp.onclick = function(i) {
if(fast || $time() > this.timer[1]) {
$clear(this.timeout);
if (fast) {
this.fx.each(function(fx) {
fx.time = 0;
fx.options.duration = 0;
fx.stop(true);
});
}
this.direction = (i < this.curr[0] || this.curr[0] === 0) ? 'right' : 'left';
this.curr[0] = i;
this.timer = [0];
this.loader = this.imgs[this.curr[0]];
this.load(fast);
}
}.pass(i, this);
this.ul.adopt(li.clone().adopt(atemp));
}
}
if (this.options.navigation.test(/arrows/)) {
this.ul.adopt(li.clone()
.adopt(a.clone()
.addClass(this.options.classes[1])
.addEvent('click', function() {
if (fast || $time() > this.timer[1]) {
$clear(this.timeout);
// Clear the FX array only for fast navigation since this stops combo effects
if (fast) {
this.fx.each(function(fx) {
fx.time = 0;
fx.options.duration = 0;
fx.stop(true);
});
}
this.timer = [0];
this.load(fast);
}
}.bind(this))
)
);
}
this.ul.injectInside(this.el);
},
onClick: function(e) {
e = new Event(e).stop();
var cur = this.curr[1] % this.imgs.length;
var index = this.curr[1] == 0 ? 1 : cur == 0 ? this.imgs.length : cur;
var url = this.options.images[index - 1].url;
if(url == '#' || url == '') return;
window.location.href = url;
},
mask: function(val, set, lower, higher) {
if(val != 'rand') {
val = val.toInt();
val = isNaN(val) || val < lower || val > higher ? set : val;
}
return val;
},
resize: function(obj, to) {
var n;
if(this.options.resize) {
n = Math.max(this.width / to.width, this.height / to.height);
obj.setStyles({
height: Math.ceil(to.height*n),
width: Math.ceil(to.width*n)
});
}
}
});
Slideshow.implement(new Options);
/**
*
*
*
*/
var ImageLoader = new Class({
version:'.5-olmo-ver',
options: {
loadingDiv : false,
loadingPrefix : 'loading images: ',
loadingSuffix : '',
path : '',
removeDiv : true
},
initialize: function(container, sources, options){
this.setOptions(options);
this.loadingDiv = (this.options.loadingDiv) ? $(container) : false;
this.images = [];
this.index = 0;
this.total = sources.length;
if(this.loadingDiv) {
this.loadingText = new Element('div').injectInside(this.loadingDiv);
this.progressBar = new Element('div', {
styles: {
width: 100,
padding: 1,
margin: '5px auto',
textAlign: 'left',
overflow: 'hidden',
border: 'solid 1px #333'
}
}).adopt(new Element('div', {
styles: {
width: '0%',
height: 10,
backgroundColor: '#333'
}
})).injectInside(this.loadingDiv);
}
this.loadImages.delay(200, this, [sources]);
},
reset: function() {
this.index = 0;
if(this.loadingDiv) {
this.progressBar.getFirst().setStyle('width', '0%');
this.loadingText.setHTML(this.options.loadingPrefix);
}
},
loadImages: function(sources) {
var self = this;
this.reset();
this.images = [];
this.sources = sources;
this.timer = setInterval(this.loadProgress.bind(this), 100);
for(var i = 0, j = sources.length; i < j; i++) {
this.images[i] = new Asset.image((this.sources[i].path || this.options.path) + this.sources[i].file, {
title: self.sources[i].title,
alt: self.sources[i].desc,
'onload' : function(){ self.index++; },
'onerror' : function(){ self.index++; self.images.splice(i,1); },
'onabort' : function(){ self.index++; self.images.splice(i,1); }
});
}
},
loadProgress: function() {
if(this.loadingDiv) {
this.loadingText.setHTML(this.options.loadingPrefix + this.index + '/' + this.total + this.options.loadingSuffix);
this.progressBar.getFirst().setStyle('width', (!this.total ? 0 : this.index.toInt()*100 / this.total) + '%');
}
if(this.index >= this.total) {
this.loadComplete();
}
},
loadComplete: function(){
$clear(this.timer);
if(this.loadingDiv) {
this.loadingText.setHTML('Loading Complete');
if(this.options.removeDiv) {
this.loadingText.empty().remove();
this.progressBar.empty().remove();
}
}
this.fireEvent('onComplete', this.images);
},
cancel: function(){
$clear(this.timer);
}
});
ImageLoader.implement(new Events, new Options);
If the slider stops on mouseover event, you can try:
$('#sliderSelector').mouseover(function (event) {
event.stopPropagation();
event.preventDefault();
});
or:
$('#sliderSelector').mouseover(function () {
return false;
});
If the function in the plugin is only stoping the slider, then it should work. If there's more behind it will probably fail.
If this is not working: can you provide plugin code? (I coudnt't find it using google)

run stack plugin on mouse hover on the div

I am using the following plugin
http://playground.mobily.pl/jquery/mobily-notes/demo.html
which gives a very good stack, but the problem is when I use it for my gallery. All of the albums are auto rotating which looks odd. Is there any possible way to at least run the plugin after we hover on the div instead of auto run? The main code to run this is
$(function(){
$('.notes_img').mobilynotes({
init: 'rotate',
showList: false,
positionMultiplier: 5
});
});
Notice: I am not the author but it's an MIT licensed plugin so there shouldn't be any problem with modifying and redistributing it here.
In spite of eye candy of the plugin, it's not elastic enough to extend.
You can use my modified version instead.
mobilynotes.js:
(function ($) {
$.fn.mobilynotes = function (options) {
var defaults = {
init: "rotate",
positionMultiplier: 5,
title: null,
showList: true,
autoplay: true,
interval: 4000,
hover: true,
index: 1
};
var sets = $.extend({}, defaults, options);
return this.each(function () {
var $t = $(this),
note = $t.find(".note"),
size = note.length,
autoplay;
var notes = {
init: function () {
notes.css();
if (sets.showList) {
notes.list()
}
if (sets.autoplay) {
notes.autoplay()
}
if (sets.hover) {
notes.hover()
}
notes.show()
},
random: function (l, u) {
return Math.floor((Math.random() * (u - l + 1)) + l)
},
css: function () {
var zindex = note.length;
note.each(function (i) {
var $t = $(this);
switch (sets.init) {
case "plain":
var x = notes.random(-(sets.positionMultiplier), sets.positionMultiplier),
y = notes.random(-(sets.positionMultiplier), sets.positionMultiplier);
$t.css({
top: y + "px",
left: x + "px",
zIndex: zindex--
});
break;
case "rotate":
var rotate = notes.random(-(sets.positionMultiplier), sets.positionMultiplier),
degrees = "rotate(" + rotate + "deg)";
$t.css({
"-webkit-transform": degrees,
"-moz-transform": degrees,
"-o-transform": degrees,
filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=" + rotate + ")",
zIndex: zindex--
})
}
$t.attr("note", i)
})
},
zindex: function () {
var arr = new Array();
note.each(function (i) {
arr[i] = $(this).css("z-index")
});
var z = Math.max.apply(Math, arr);
return z
},
list: function () {
$t.after($("<ul />").addClass("listNotes"));
var ul = $t.find(".listNotes"),
title = new Array();
if (sets.title != null) {
note.each(function (i) {
title[i] = $(this).find(sets.title).text()
})
} else {
title[0] = "Bad selector!"
}
for (x in title) {
$t.next(".listNotes").append($("<li />").append($("<a />").attr({
href: "#",
rel: x
}).text(title[x])))
}
},
autoplay: function () {
var i = 1,
autoplay = setInterval(function () {
i == size ? i = 0 : "";
var div = note.eq(i),
w = div.width(),
left = div.css("left");
notes.animate(div, w, left);
i++
}, sets.interval)
},
hover: function () {
$t.hover(function() {
var div = note.eq(sets.index),
w = div.width(),
left = div.css("left");
sets.index == size ? sets.index = 1 : sets.index += 1;
notes.animate(div, w, left);
},
function() {}
);
},
show: function () {
$t.next(".listNotes").find("a").click(function () {
var $t = $(this),
nr = $t.attr("rel"),
div = note.filter(function () {
return $(this).attr("note") == nr
}),
left = div.css("left"),
w = div.width(),
h = div.height();
clearInterval(autoplay);
notes.animate(div, w, left);
return false
})
},
animate: function (selector, width, position) {
var z = notes.zindex();
selector.animate({
left: width + "px"
}, function () {
selector.css({
zIndex: z + 1
}).animate({
left: position
})
})
}
};
notes.init()
})
}
}(jQuery));
Using new features:
$('.notes_img').mobilynotes({
init: 'rotate',
showList: false,
autoplay: false,
index: 1, //starting index (new)
hover: true // (new)
});
Taking over where #username left off (excellent work), I have branched username's fiddle with the following changes to the config options:
Modified (from #username's code):
hover: (boolean) on hover, reverses the effect of autoplay
New:
click: (boolean) on click, advances to next note, then resumes autoplay, if active, in the hover state.
Internally, new next, stop and restart functions and modified init, autoplay and animate functions handle (combinations of) the options.
The trickiest part was to provide for a callback in animate to cause autoplay to resume after next (the click action) has completed. This has ramifications in several other functions. (On reflection there's undoubtedly a better way using deferreds - I will have a think about that)
Here's the fiddle (or this full page version), with settings that reflect #Sakshi Sharma original question. I set click to true but it could equally be set to false, depending on preference.
And here's the code:
(function($) {
$.fn.mobilynotes = function(options) {
var defaults = {
init: "rotate",
positionMultiplier: 5,
title: null,
showList: true,
autoplay: false,
hover: true,//when true, hovering reverses autoplay; when false, has no effect.
click: true,
interval: 4000,
index: 1
};
var settings = $.extend({}, defaults, options);
return this.each(function() {
var $t = $(this),
note = $t.find(".note"),
size = note.length,
autoplay,
currentIndex = 1;
var notes = {
init: function() {
notes.css();
if (settings.showList) {
notes.list();
}
if (settings.hover) {
var fn1 = settings.autoplay ? notes.stop : notes.restart;
var fn2 = settings.autoplay ? notes.restart : notes.stop;
$t.hover(fn1, fn2);
}
if (settings.click) {
clearInterval(autoplay);
//autoplay 0, hover 0: null
//autoplay 0, hover 1: autoplay
//autoplay 1, hover 0: autoplay
//autoplay 1, hover 1: null
var callback = ( (settings.autoplay && !settings.hover) || (!settings.autoplay && settings.hover) ) ? notes.autoplay : null;
$t.click(function(){
notes.next(callback);
});
}
if (settings.autoplay) {
notes.autoplay();
}
notes.show();
},
random: function(l, u) {
return Math.floor((Math.random() * (u - l + 1)) + l);
},
css: function() {
var zindex = note.length;
note.each(function(i) {
var $t = $(this);
switch (settings.init) {
case "plain":
var x = notes.random(-(settings.positionMultiplier), settings.positionMultiplier),
y = notes.random(-(settings.positionMultiplier), settings.positionMultiplier);
$t.css({
top: y + "px",
left: x + "px",
zIndex: zindex--
});
break;
case "rotate":
var rotate = notes.random(-(settings.positionMultiplier), settings.positionMultiplier),
degrees = "rotate(" + rotate + "deg)";
$t.css({
"-webkit-transform": degrees,
"-moz-transform": degrees,
"-o-transform": degrees,
filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=" + rotate + ")",
zIndex: zindex--
})
}
$t.attr("note", i)
});
},
zindex: function() {
var arr = new Array();
note.each(function(i) {
arr[i] = $(this).css("z-index")
});
var z = Math.max.apply(Math, arr);
return z
},
list: function() {
$t.after($("<ul />").addClass("listNotes"));
var ul = $t.find(".listNotes"),
title = new Array();
if (settings.title != null) {
note.each(function(i) {
title[i] = $(this).find(settings.title).text()
})
} else {
title[0] = "Bad selector!"
}
for (x in title) {
$t.next(".listNotes").append($("<li />").append($("<a />").attr({
href: "#",
rel: x
}).text(title[x])))
}
},
next: function(callback) {
callback = (!callback || typeof callback !== 'function') ? null : callback;
currentIndex = currentIndex % size;
notes.animate(note.eq(currentIndex), callback);
currentIndex++;
},
autoplay: function() {
notes.stop();
autoplay = setInterval(notes.next, settings.interval);
},
stop: function() {
clearInterval(autoplay);
},
restart: function() {
notes.next(notes.autoplay);
},
show: function() {
$t.next(".listNotes").find("a").click(function() {
var $t = $(this),
nr = $t.attr("rel"),
div = note.filter(function() {
return $(this).attr("note") == nr;
});
clearInterval(autoplay);
notes.animate(div);
return false;
})
},
animate: function(selector, callback) {
var width = selector.width(),
position = selector.css("left"),
z = notes.zindex();
selector.animate({
left: width + "px"
}, function() {
selector.css({
zIndex: z + 1
}).animate({
left: position
}, function(){
if(callback) {
callback();
}
});
});
}
};
notes.init()
})
}
}(jQuery));
Hiya there so demo here :) and hope this helps: http://jsfiddle.net/haf6J/14/show/ && http://jsfiddle.net/haf6J/14/ OR http://jsfiddle.net/haf6J/3/show/ && http://jsfiddle.net/haf6J/3/
Now the rotation will start when you hover the images and if you want further that one mouse out it should stop you can take a look into event .mouseout and you can stop the rotation i.e. remove the effect.
Like epascarello mentioned documentation is here http://playground.mobily.pl/jquery/mobily-notes.html
Please let me know and dont forget to accept if this helps (and upvote :)) cheers
Jquery Code
$('.notes_img').hover(function() {
$('.notes_img').mobilynotes({
init: 'rotate',
showList: false
});
});​

Making a slider without recursion

Given the following jsFiddle, how can I implement the same effect as I have made without building on the stack?
http://jsfiddle.net/YWMcy/1/
I tried doing something like this:
jQuery(document).ready(function () {
'use strict';
(function ($) {
function validateOptions(options) {
if (typeof(options.delay) == typeof(0)) {
$.error('Delay value must an integer.');
return false;
} else if (options.delay < 0) {
$.error('Delay value must be greater than zero.');
return false;
}
if (typeof(options.direction) == typeof('')) {
$.error('Direction value must be a string.');
return false;
} else if (!(options.direction in ['left', 'right', 'up', 'down'])) {
$.error('Direction value must be "left", "right", "up", or "down".');
return false;
}
if (typeof(options.easing) == typeof('')) {
$.error('Easing value must be a string.');
return false;
}
if (typeof(options.selector) == typeof('')) {
$.error('Selector value must be a string.');
return false;
}
if (options.transition < 0) {
$.error('Transition value must be greater than zero.');
return false;
}
return true;
}
var methods = {
init: function (options) {
return this.each(function () {
var settings = {
delay: 5000,
direction: 'left',
easing: 'swing',
selector: '*',
transition: 3000
};
if (options) {
$.extend(settings, options);
}
$(this).css({
overflow: 'hidden',
position: 'relative'
});
var styles = {
left: 0,
position: 'absolute',
top: 0
};
switch (settings.direction) {
case 'left':
styles.left = $(this).width() + 'px';
break;
case 'right':
styles.left = -$(this).width() + 'px';
break;
case 'up':
styles.top = $(this).height() + 'px';
break;
case 'down':
styles.top = -$(this).height() + 'px';
break;
default:
jQuery.error('Direction ' + settings.direction + ' is not valid for jQuery.fn.cycle');
break;
}
$(this).children(settings.selector).css(styles).first().css({
left: 0,
top: 0
});
if ($(this).children(settings.selector).length > 1) {
$(this).cycle('slide', settings);
}
});
},
slide: function (options) {
return this.each(function () {
var settings = {
delay: 5000,
direction: 'left',
easing: 'swing',
selector: '*',
transition: 3000
}, animation, property, value;
if (options) {
$.extend(settings, options);
}
switch (settings.direction) {
case 'left':
animation = {left: '-=' + $(this).width()};
property = 'left';
value = $(this).width();
break;
case 'right':
animation = {left: '+=' + $(this).width()};
property = 'left';
value = -$(this).width();
break;
case 'up':
animation = {top: '-=' + $(this).height()};
property = 'top';
value = $(this).height();
break;
case 'down':
animation = {top: '+=' + $(this).height()};
property = 'top';
value = -$(this).height();
break;
default:
jQuery.error('Direction ' + settings.direction + ' is not valid for jQuery.fn.cycle');
break;
}
$(this).children(settings.selector + ':first-child').each(function () {
$(this).delay(settings.delay);
$(this).animate(
animation,
settings.transition,
settings.easing,
function () {
$(this).css(property, value);
}
);
});
$(this).append($(this).children(settings.selector + ':first-child').detach());
$(this).children(settings.selector + ':first-child').each(function () {
$(this).delay(settings.delay);
$(this).animate(
animation,
settings.transition,
settings.easing,
function () {
$(this).parent().cycle('slide', settings);
}
);
});
});
}
};
jQuery.fn.cycle = function (method, options) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.fn.cycle');
}
};
}(jQuery));
jQuery('.slider').cycle();
});
But the each() method does not take into account nodes that are added during the loop.
You can launch your _cycle() function through setInterval(), to periodically update the slider:
setInterval(function() {
_cycle2(slider, transition_duration, easing);
}, delay_duration);
Note that I renamed your original _cycle() function to _cycle2(), and removed the delay_duration parameter. You can see a working demo here.
You don't want anything resembling while(true).
Your problem stems from the fact that you're creating a static function and then trying to figure out how to animate the children with the constraint of keeping it all in scope of your static function.
You should instead create an instance of an object per element, let the object maintain the state of the slider and have it update that state via an implementation necessary for the slider to operate.
http://jsfiddle.net/qjVJF/3/
(function ($) {
var $b = $.behaviors || {};
$b.slider = function(element, options) {
this.element = $(element);
this.panels = this.element.find('.slide');
this.options = $.extend({}, $b.slider.defaults, options);
this.currentPanel = 0;
var horizontal = (this.options.direction == 'left' || this.options.direction == 'right');
var anti = (this.options.direction == 'left' || this.options.direction == 'up');
var distance = horizontal ? '600' : '150';
this.action = anti ? '-='+distance : '+='+distance;
this.origin = anti ? distance : 0-distance;
this.edge = horizontal ? 'left' : 'top';
this.animation = horizontal ? { "left": this.action } : { "top" : this.action };
this.panels.css(this.edge, this.origin+'px').show().first().css(this.edge, '0px');
this.delayNext();
return this;
}
$b.slider.defaults = {
delay: 500,
direction: 'left',
easing: 'swing',
transition: 3000
};
$b.slider.prototype = {
delayNext: function() {
setTimeout($.proxy(this.slideNext, this), this.options.delay);
},
slideNext: function() {
var current = this.panels[this.currentPanel % this.panels.length];
var next = $(this.panels[++this.currentPanel % this.panels.length])
.css(this.edge, this.origin+'px');
var plugin = this;
next.add(current).animate(
this.animation,
this.options.transition,
this.options.easing,
function() {
if (this == current) plugin.delayNext();
}
);
}
};
$.fn.cycle = function (options) {
return this.each(function() {
$(this).data('bCycle', new $b.slider(this, options));
});
};
}(jQuery));
jQuery(document).ready(function () {
jQuery('.slider').cycle();
});
Maybe this plugin http://docs.jquery.com/Plugins/livequery can help you?
Live Query utilizes the power of jQuery selectors by binding events or firing callbacks for matched elements auto-magically, even after the page has been loaded and the DOM updated.
For example you could use the following code to bind a click event to all A tags, even any A tags you might add via AJAX.
$('a')
.livequery('click', function(event) {
alert('clicked');
return false;
});

Categories

Resources