I have a jQuery slideshow plugin that I am making though it has a setInterval() inside it which is not being called though if I move the contents of the setInterval() outside of the it then it works though it only runs once.
var gap = 3;
var duration = 0.5;
(function ($) {
$.fn.slideshow = function () {
return this.each(function () {
g = gap * 1000;
d = duration * 1000;
$(this).children().css({
'position': 'absolute',
'display': 'none'
});
$(this).children().eq(0).css({
'display': 'block'
});
setInterval(function () {
slide();
}, g);
function slide() {
$(this)
.children()
.eq(0)
.fadeOut(d)
.next()
.fadeIn()
.end()
.appendTo($(this).children().eq(0).parent());
}
});
};
})(jQuery);
$('.slideshow').slideshow();
HTML:
<div class='slideshow'>
<a>1</a>
<a>2</a>
<a>3</a>
<a>4</a>
</div>
Here is a fiddle with my plugin:
http://jsfiddle.net/Hive7/GrtLC/
The problem is this inside the slider function does not point to the object you think it points to.
setInterval($.proxy(function () {
slide.call(this);
}, this), g);
Demo: Fiddle
or better
setInterval($.proxy(slide, this), g);
Demo: Fiddle
Your problem is that this is always locally defined; by the time you get into the setInterval(), you've lost your original this (it's reset to the window object).
There are a few ways to get around this; the simplest is probably to copy this into a local variable.
http://jsfiddle.net/mblase75/GrtLC/5/
var gap = 3;
var duration = 0.5;
(function ($) {
$.fn.slideshow = function () {
return this.each(function () {
g = gap * 1000;
d = duration * 1000;
$this = $(this); // caches the jQuery object as a further optimization
$this.children().css({
'position': 'absolute',
'display': 'none'
});
$this.children().eq(0).css({
'display': 'block'
});
setInterval(function () {
slide($this); // pass $this into the function
}, g);
function slide($obj) {
$obj.children()
.eq(0)
.fadeOut(d)
.next()
.fadeIn()
.end()
.appendTo($obj.children().eq(0).parent());
}
});
};
})(jQuery);
$('.slideshow').slideshow();
Your code cannot work, because your callback is not bound to the this; try instead
var that = this;
setInterval(function () {
slide();
}, g);
function slide() {
$(that) ....
this inside slide function is not the slideshow. I make it work caching the object inside the each loop: http://jsfiddle.net/x7Jk8/
Related
Can I use nested jquery.proxy?
var obj = {
init: function(element){
element.on('click.mynamespace',$.proxy(function (event) {
$(event.currentTarget).animate({
scrollLeft: scrollPos
}, width, $.proxy(this.myFunction,this));
},this))
},
myFunction: function(){
/*some code*/
}
}
This is what I need for my project. I have used the nested $.proxy to make the code work. Because I need this context in myFunction which is a callback function for jquery animate api.
Can I use in this way?
It should work, however I'd suggest that storing a reference to the object in the outer scope would be a more elegant solution. Note the definition and use of _obj in this example:
var scrollPos = 10;
var width = 20;
var obj = {
init: function($element) {
var _obj = this;
$element.on('click.mynamespace', function(e) {
$(this).animate({
scrollLeft: scrollPos
}, width, _obj.myFunction.call(this));
});
},
myFunction: function() {
// this function now executes within the context of the
// element which has been animated in the click handler
console.log(this.id);
}
}
var $foo = $('#foo');
obj.init($foo);
$foo.trigger('click.mynamespace');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo"></div>
What I am trying to do is only run my code when someone has hovered on an element for 1 second.
Here is the code that I am using:
var timer;
$(".homeLinkWrap").mouseenter(function() {
timer = setTimeout(function(){
$(this).find('.homeLinkNfo').removeClass('flipOutY').addClass('flipInY').css({opacity: '1'});
console.log('in');
}, 1000);
}).mouseleave(function() {
$(this).find('.homeLinkNfo').removeClass('flipInY').addClass('flipOutY');
console.log('out');
clearTimeout(timer);
});
The first part (mouseenter) IS NOT functioning and DOESN'T remove the class and then add the new one. The second one (mouseleave) IS functioning properly and DOES remove the class and add the new one.
I am guessing it is because I am targeting $(this) which is the current element being hovered over and since it is in a timer function jQuery doesn't know which element $(this) is referring to.
What can I do to remedy this?
I think it is because you are calling $(this) inside the setTimeout function. You need to do something like this:
$(".homeLinkWrap").mouseenter(function() {
var $self = $(this);
timer = setTimeout(function(){
$self.find('.homeLinkNfo').removeClass('flipOutY').addClass('flipInY').css({opacity: '1'});
console.log('in');
}, 1000);
});
Inside the setTimeout callback, this no longer refers to the jQuery selection. You should either keep a reference to the selection:
$(".homeLinkWrap").mouseenter(function() {
var $this = $(this);
timer = setTimeout(function(){
$this.find('.homeLinkNfo').removeClass('flipOutY').addClass('flipInY').css({opacity: '1'});
console.log('in');
}, 1000);
})
Or use an arrow function (ES2015)
$(".homeLinkWrap").mouseenter(function() {
timer = setTimeout(() => {
$(this).find('.homeLinkNfo').removeClass('flipOutY').addClass('flipInY').css({opacity: '1'});
console.log('in');
}, 1000);
})
The problem here is that the this inside the callback function that you're passing to setTimeout doesn't reference to the same point that the this outside the callback does.
There are some ways of solving your problem, I'll suggest you to use Function.prototype.bind to bind your callback function to the same this you have outside:
var timer;
$(".homeLinkWrap").mouseenter(function() {
timer = setTimeout((function() {
$(this).find('.homeLinkNfo').removeClass('flipOutY').addClass('flipInY').css({ opacity: '1' });
}).bind(this), 1000);
}).mouseleave(function() {
$(this).find('.homeLinkNfo').removeClass('flipInY').addClass('flipOutY');
clearTimeout(timer);
});
I'm trying to loop an "animation" of adding and removing classes:
function loading() {
$('#loading').removeClass().addClass('load0').delay(5000).removeClass().addClass('load1').delay(5000).removeClass().addClass('load2').delay(5000).removeClass().addClass('load3').delay(5000, loading);
}
loading();
Two problems:
It doesn't appear that removeClass() and addClass() can be queued with delay().
delay() doesn't appear to accept a callback function.
How can I do this?
var l = $('#loading'),
i = 0;
(function loading() {
l.removeClass().addClass('load' + i);
i = ++i % 4;
setTimeout(loading, 5000);
})();
Or we can encapsulate the variables too.
(function loading(l, i) {
l.removeClass().addClass('load' + i);
setTimeout(function() {
loading(l, ++i % 4);
}, 5000);
})($('#loading'), 0);
Modern browsers make this a little cleaner.
(function loading(l, i) {
l.removeClass().addClass('load' + i);
setTimeout(loading, 5000, l, ++i % 4);
})($('#loading'), 0);
You cannot use delay for non animating functions
Using setTimeout instead with your own callbacks might work out better.
If we're trying to loop animations why not loop animations using the .animate() with callbacks?
Example Fiddle:
http://jsfiddle.net/Culyx/fsxpZ/1/
The "arrow" in the fiddle used to be an image just a place holder div at the moment; but that should be another way of looping animations in jquery. Code for the looping animations:
$(document).ready(function () {
//looping bouncing arrow animation and speed controls
var arrowSpeed = 400;
bounceLeft = function () {
$(".arrow").animate({
left: "+=50px"
}, {
duration: arrowSpeed,
complete: bounceRight
});
}
bounceRight = function () {
$(".arrow").animate({
left: "-=50px"
}, {
duration: arrowSpeed,
complete: bounceLeft
});
}
bounceLeft();
});
$('#test').hover(
function () {
$(this).append('Blah');
}
);
How can I make the jQuery repeatedly append Blah in #test based on how long you are hovering over #test?
For instance, how can I append Blah once every second you are hovering over #test?
You could use setInterval like this :
var myInterval = false;
$('#test').hover(
function(){
$that = $(this);
// need to save $(this) as 'this' will be different within setInterval
myInterval = setInterval(function(){
$that.append('Blah');
}, 100); // repeat every 100 ms
},function() {
clearInterval(myInterval); // clear the interval on hoverOut
}
);
Working example here
(function() {
var intv;
$('#test').hover(
function () {
var $this = $(this);
intv = setInterval(function() {
$this.append('Blah');
}, 1000);
},
function() {
clearInterval(intv);
}
);
}());
I've enclosed all the code inside a anonymous scoped function so to not pollute global scope, and I cached a reference to $(this) to avoid a new evaluation every second, inside the timeout
You can use setInterval to do so:
var appending; //var to store the interval
$('#test').hover(function(){ //on mouseenter
var $this = $(this); //store the context, i.e. the element triggering the hover
appending = setInterval(function(){ //the following function gets executed every second until the interval is cleared
$this.append('<p>Blah</p>'); //append content to context
},1000); //1000 meaning the repetition time in ms
},function(){ //on mouseleave
clearInterval(appending); //clear the interval on mouseleave
});
use setInterval()
$('#test').hover(
function () {
setInterval(function() {
$(this).append('Blah');
},1000)
}
);
I'm trying to create an animation sequence with jQuery where one animation starts after the previous one is done. But I just can't wrap my head around it. I've tried to make use of the jQuery.queue, but I don't think I can use that because it seems to have one individual queue for each element in the jQuery array.
I need something like:
$('li.some').each(function(){
// Add to queue
$(this).animate({ width: '+=100' }, 'fast', function(){
// Remove from queue
// Start next animation
});
});
Is there a jQuery way to do this or do I have to write and handle my own queue manually?
You can make a custom .queue() to avoid the limitless nesting..
var q = $({});
function animToQueue(theQueue, selector, animationprops) {
theQueue.queue(function(next) {
$(selector).animate(animationprops, next);
});
}
// usage
animToQueue(q, '#first', {width: '+=100'});
animToQueue(q, '#second', {height: '+=100'});
animToQueue(q, '#second', {width: '-=50'});
animToQueue(q, '#first', {height: '-=50'});
Demo at http://jsfiddle.net/gaby/qDbRm/2/
If, on the other hand, you want to perform the same animation for a multitude of elements one after the other then you can use their index to .delay() each element's animation for the duration of all the previous ones..
$('li.some').each(function(idx){
var duration = 500;
$(this).delay(duration*idx).animate({ width: '+=100' }, duration);
});
Demo at http://jsfiddle.net/gaby/qDbRm/3/
The callback of .animate() actually accepts another .animate(), so all you would have to do would be
$(this).animate({ width: '+=100' }, 'fast', function(){
$(selector).animate({attr: val}, 'speed', function(){
});
});
and so on.
You could call the next one recursively.
function animate(item) {
var elem = $('li.some').eq(item);
if(elem.length) {
elem.animate({ width: '+=100' }, 'fast', function() {
animate(item + 1);
});
}
}
animate(0);
why not build up a queue?
var interval = 0; //time for each animation
var speed = 200;
$('li.some').each(function(){
interval++;
$(this).delay(interval * speed).animate({ width: '+=100' }, speed);
});
EDIT: added speed param
Thanks to everybody replying!
I thought I should share the outcome of my question. Here is a simple jQuery slideDownAll plugin that slides down one item at a time rather than all at once.
(function ($) {
'use strict';
$.fn.slideDownAll = function (duration, callback) {
var that = this, size = this.length, animationQueue = $({});
var addToAnimationQueue = function (element, duration, easing, callback) {
animationQueue.queue(function (next) {
$(element).slideDown(duration, easing, function () {
if (typeof callback === 'function') {
callback.call(this);
}
next();
});
});
};
return this.each(function (index) {
var complete = null,
easing = 'linear';
if (index + 1 === size) {
complete = callback;
easing = 'swing';
}
addToAnimationQueue(this, duration / size, easing, complete);
});
};
} (jQuery));
Not very well test, but anyways.
Enjoy!!