run stack plugin on mouse hover on the div - javascript

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

Related

How can i stop videos when i go to next slide

website is: ortakbilinc.com You can see the slider on homepage. When i click to next slide video continues to playing. How can i fix it. I'm trying everything but i couldnt handle.
website is: ortakbilinc.com You can see the slider on homepage. When i click to next slide video continues to playing. How can i fix it. I'm trying everything but i couldnt handle.
Feature Slider
-------------------------------------------------*/
if ($('.feature-slider').length) {
$('.feature-slider').each(function() {
var t = $(this);
if (!t.hasClass('gallery-post-slider')) {
var animation = t.data('sanimation');
var speed = t.data('speed');
var timeout = t.data('timeout');
var easing = t.data('easing');
var rndn = t.data('rndn');
var rtl = false;
var autoplay = t.data('autoplay');
var items = t.data('items');
var animation_new = t.data('animation_new');
var animation_in = t.data('animation_in');
var animation_out = t.data('animation_out');
var margin = 10;
var auto_height = 0;
var thumbs_event = t.data('thumbs_event');
if(typeof thumbs_event === 'undefined'){
thumbs_event = 'click';
}
if (t.hasClass('no_spaces')) {
margin = 5;
auto_height = 1;
}
t.find('.fs-image-nav .fs-thumb').each(function(i) {
$(this).addClass( 'item'+i );
if (t.hasClass('old-style')) {
$(this).click(function() {
t.find('.fslides').trigger( 'slideTo', [i, 0, true] );
return false;
});
}
});
t.find('.fs-image-nav .fs-thumb.item0').addClass( 'active' );
var carou_items = 6;
if ($(window).width() < 768) {
carou_items = 5;
}
if ($(window).width() < 568) {
carou_items = 4;
}
if ($(window).width() < 480 ) {
carou_items = 2;
}
if ($('body').hasClass('rtl')) {
rtl = true;
}
if (!t.hasClass('old-style')) {
var owl = t.find('.fslides');
var slides_count = owl.children('.fslide').length;
if (slides_count == 1) {
t.addClass('fs-with-one-slide');
}
if (slides_count > 1) {
owl.owlCarousel({
items: 1,
baseClass: 'mom-carousel',
rtl: rtl,
autoplay:autoplay,
autoplayTimeout:timeout,
autoplayHoverPause : false,
loop: true,
animateOut: animation_out,
animateIn: animation_in,
smartSpeed:1000,
//autoHeight: true,
});
t.find('.fslides').imagesLoaded( function() {
t.find('.fs-image-nav .fs-thumbs').owlCarousel({
items: items,
baseClass: 'mom-carousel',
rtl: rtl,
loop: true,
margin : margin,
});
//var thumb_height = t.find('.fs-image-nav .fs-thumbs .fs-thumb').eq(0).css('height');
//t.find('.fs-image-nav .fs-thumbs').css('max-height', thumb_height);
owl.on('changed.owl.carousel', function(event) {
var pos = $(event.target).find(".fslide").eq(event.item.index).data('i');
//console.log(pos);
$('.fc-nav-'+rndn+' .fs-thumb').removeClass( 'active' );
$('.fc-nav-'+rndn+' .fs-thumb.item'+pos).addClass( 'active' );
var page = Math.floor( pos / items );
t.find('.fs-image-nav .fs-thumbs').trigger( 'to.owl.carousel', page );
});
t.find('.fs-image-nav .fs-thumb').on(thumbs_event, function() {
var i = $(this).data('i');
owl.trigger('to.owl.carousel', [i]);
});
t.find('.fs-image-nav .fs-prev, .fsd-prev').click(function() {
owl.trigger('prev.owl.carousel');
});
t.find('.fs-image-nav .fs-next, .fsd-next').click(function() {
owl.trigger('next.owl.carousel');
});
});
}
} else {
t.find('.fslides').carouFredSel({
circular: true,
responsive: true,
swipe: {
onTouch: true,
fx : 'scroll'
},
items: 1,
auto: {
play: autoplay,
duration: speed,
timeoutDuration: timeout,
},
prev: '.fc-nav-'+rndn+' .fs-prev, .fs-dnav-'+rndn+' span.fsd-prev',
next: '.fc-nav-'+rndn+' .fs-next, .fs-dnav-'+rndn+' span.fsd-next',
pagination: '.fs-nav-'+rndn,
scroll: {
fx: animation,
duration : speed,
easing : easing,
pauseOnHover : true,
onBefore: function() {
var pos = $(this).triggerHandler( 'currentPosition' );
$('.fc-nav-'+rndn+' div').removeClass( 'active' );
$('.fc-nav-'+rndn+' div.item'+pos).addClass( 'active' );
var page = Math.floor( pos / carou_items );
$('.fc-nav-'+rndn+' .fs-thumbs').trigger( 'slideToPage', page );
},
onAfter: function() {
}
}
});
t.find('.fs-image-nav .fs-thumbs').carouFredSel({
auto: false,
circular:true,
responsive: true,
swipe: {
onTouch: true
},
items: carou_items,
scroll: {
items:carou_items,
}
});
}
} //if not the post gallery
});

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

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

Add Multiple Elements to Page

I have created a JQuery tooltip plugin and I am applying it to a few A tags.
For each A tag there should be a different tooltip associated with it so I have:
var $tooltip = $("<div>").attr("id", tooltip.id).attr("class", options.class).appendTo('body');
Where the tooltip id includes a random number created as follows:
id: "Tooltip_" + Math.floor(Math.random() * (9999 - 2000 + 1) + 2000)
The plugin does not behave well. I checked the HTML added to the page.
Only one tooltip is being added to the page ... Always the same.
How can I fix this? What am I doing wrong?
I have an example in: http://codepen.io/mdmoura/pen/wgapv
And the plugin code is the following:
$(document).ready(function () {
$("table a").Tooltip();
});
// Tooltip
(function ($) {
$.fn.Tooltip = function (options) {
var defaults = {
class: 'Tooltip',
delay: [200, 200],
offset: [0, -10],
hide: function ($element, $tooltip) {
$tooltip.fadeOut(200);
},
show: function ($element, $tooltip) {
$tooltip.fadeIn(200);
}
};
var options = $.extend({}, defaults, options);
var tooltip = { id: "Tooltip_" + Math.floor(Math.random() * (9999 - 2000 + 1) + 2000), ready: false, timer: null, title: '' };
$(this).each(function (e) {
var $this = $(this);
tooltip.title = $this.attr('title') || '';
$this.mouseenter(function (e) {
if (tooltip.ready) {
var $tooltip = $("#" + tooltip.id);
} else {
var $tooltip = $("<div>").attr("id", tooltip.id).attr("class", options.class).appendTo('body');
$tooltip.html(tooltip.title);
tooltip.ready = true;
$this.attr('title', '');
}
var position = [e.clientX + options.offset[0], e.clientY + options.offset[1]];
$tooltip.css({ left: position[0] + 'px', top: position[1] + 'px' });
tooltip.timer = window.setTimeout(function () {
options.show($this, $tooltip.stop(true, true));
}, options.delay[0] || 0);
$("#" + tooltip.id).mouseenter(function () {
window.clearTimeout(tooltip.timer);
tooltip.timer = null;
}); // Tooltip enter
$("#" + tooltip.id).mouseleave(function () {
tooltip.timer = setTimeout(function () {
options.hide($this, $tooltip);
}, 0);
});
}), // Mouse enter
$this.mouseleave(function (e) {
tooltip.timer = setTimeout(function () {
options.hide($this, $("#" + tooltip.id).stop(true, true));
}, options.delay[1] || 0);
}) // Mouse leave
}); // Each
}; // Tooltip
})(jQuery); // JQuery
And the HTMl is the following:
<table>
<tr><td>Tooltip 01</td></tr>
<tr><td>Tooltip 02</td></tr>
<tr><td>Tooltip 03</td></tr>
<tr><td>Tooltip 04</td></tr>
<tr><td>Tooltip 05</td></tr>
</table>
Thank you!
you have the var tooltip definded outside the this.each loop, which means there will be only one tooltip instance
(function ($) {
$.fn.Tooltip = function (options) {
var defaults = {
class: 'Tooltip',
delay: [200, 200],
offset: [0, -10],
hide: function ($element, $tooltip) {
$tooltip.fadeOut(200);
},
show: function ($element, $tooltip) {
$tooltip.fadeIn(200);
}
};
var options = $.extend({}, defaults, options);
$(this).each(function (e) {
//moved this inside the loop
var tooltip = { id: "Tooltip_" + Math.floor(Math.random() * (9999 - 2000 + 1) + 2000), ready: false, timer: null, title: '' };
var $this = $(this);
tooltip.title = $this.attr('title') || '';
$this.mouseenter(function (e) {
if (tooltip.ready) {
var $tooltip = $("#" + tooltip.id);
} else {
var $tooltip = $("<div>").attr("id", tooltip.id).attr("class", options.class).appendTo('body');
$tooltip.html(tooltip.title);
tooltip.ready = true;
$this.attr('title', '');
}
var position = [e.clientX + options.offset[0], e.clientY + options.offset[1]];
$tooltip.css({ left: position[0] + 'px', top: position[1] + 'px' });
tooltip.timer = window.setTimeout(function () {
options.show($this, $tooltip.stop(true, true));
}, options.delay[0] || 0);
$("#" + tooltip.id).mouseenter(function () {
window.clearTimeout(tooltip.timer);
tooltip.timer = null;
}); // Tooltip enter
$("#" + tooltip.id).mouseleave(function () {
tooltip.timer = setTimeout(function () {
options.hide($this, $tooltip);
}, 0);
});
}), // Mouse enter
$this.mouseleave(function (e) {
tooltip.timer = setTimeout(function () {
options.hide($this, $("#" + tooltip.id).stop(true, true));
}, options.delay[1] || 0);
}) // Mouse leave
}); // Each
}; // Tooltip
})(jQuery);
Demo: CodePen

jQuery Error on Plugin?

On my site my browser crashes when viewing a web page, It says its my script on line 21 only Im unsure whats wrong? Can anybody see a problem?
jQuery.fn.carousel = function(previous, next, options){
var sliderList = jQuery(this).children()[0];
if (sliderList) {
var increment = jQuery(sliderList).children().outerWidth("true"),
elmnts = jQuery(sliderList).children(),
numElmts = elmnts.length,
sizeFirstElmnt = increment,
shownInViewport = Math.round(jQuery(this).width() / sizeFirstElmnt),
firstElementOnViewPort = 1,
isAnimating = false;
for (i = 0; i < shownInViewport; i++) {
jQuery(sliderList).css('width',(numElmts+shownInViewport)*increment + increment + "px");
jQuery(sliderList).append(jQuery(elmnts[i]).clone());
}
jQuery(previous).click(function(event){
if (!isAnimating) {
if (firstElementOnViewPort == 1) {
jQuery(sliderList).css('left', "-" + numElmts * sizeFirstElmnt + "px");
firstElementOnViewPort = numElmts;
}
else {
firstElementOnViewPort--;
}
jQuery(sliderList).animate({
left: "+=" + increment,
y: 0,
queue: true
}, "swing", function(){isAnimating = false;});
isAnimating = true;
}
});
jQuery(next).click(function(event){
if (!isAnimating) {
if (firstElementOnViewPort > numElmts) {
firstElementOnViewPort = 2;
jQuery(sliderList).css('left', "0px");
}
else {
firstElementOnViewPort++;
}
jQuery(sliderList).animate({
left: "-=" + increment,
y: 0,
queue: true
}, "swing", function(){isAnimating = false;});
isAnimating = true;
}
});
}
};
Line 21 is
jQuery(sliderList).append(jQuery(elmnts[i]).clone());
I call my plugin with...
$('.viewer').each(function() {
$(this).carousel('.viewer .simplePrevious', '.viewer .simpleNext');
});
Is it on an HTML5 element and in IE?
I have had a similar problem, even with html5shiv. had to revert to xhtml for it to work again.

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