jQuery create interval within each cant access $(this) - javascript

i have three different image-slides on my website. The number of images inside the slide is generated from wordpress.
I need to check if a slide contains more elements than one, if yes then a slideshow has to start. Now i've got a problem i created the interval inside the jQuery each function and inside the interval i can't access the $(this) from the each. So nothing is happening when the interval is called.
$( ".home .images .image-slide div" ).each(function() {
var count = $(this).children().length;
if (count > 1) {
$(this).find("img:first-child").addClass("active");
setInterval(function(){
if($(this).find('.active').is(":last-child")){
$(this).find('.active').removeClass("active").fadeOut().parent().find("img:first-child").addClass("active").fadeIn();
} else {
$(this).find('img.active').removeClass("active").fadeOut().next().fadeIn().addClass("active");
}
}, 4000);
}
});
How can i access the inside the interval with $(this)?

As Marie pointed in the comments, you need to work around the closure.
Here is a simple way to make it work, by moving the $(this) outside of the setInterval.
$( ".home .images .image-slide div" ).each(function() {
var count = $(this).children().length;
if (count > 1) {
$(this).find("img:first-child").addClass("active");
var self = $(this);
setInterval(function(){
if(self.find('.active').is(":last-child")){
self.find('.active').removeClass("active").fadeOut().parent().find("img:first-child").addClass("active").fadeIn();
} else {
self.find('img.active').removeClass("active").fadeOut().next().fadeIn().addClass("active");
}
}, 4000);
}
});

Related

Show popup on hover only if i hover on li after 1 second

I'm trying to show inner div on hover on li. I'm doing fadeIn and fadeOut effect but the problem is when I hover quickly on all li fadeIn effect work for all. Where it should show only if I hover on li for 1 second and if I leave that element before one second it shouldn't show fadein effect.
<script type="text/javascript">
$(document).ready(function(){
var _changeInterval = null;
$( ".badge_icon" ).hover(function() {
clearInterval(_changeInterval)
_changeInterval = setInterval(function() {
$(this).find(".badges_hover_state").fadeIn(500);
}, 1000);
},function() {
$(this).find('.badges_hover_state').fadeOut(500);
});
});
</script>
I have tried to use stop(), delay() also but didn't get success. At last I tried to do with time interval but now my code has stopped working.
you could use this jquery script:
var myTimeout;
$('#div').mouseenter(function() {
myTimeout = setTimeout(function() {
//Do stuff
}, 1000);
}).mouseleave(function() {
clearTimeout(myTimeout);
});
See the DEMO
Was able to solve this issue by adding window in front of variable name.
var myTimeout;
$('.div').mouseenter(function() {
window.el = $(this);
myTimeout = setTimeout(function() {
el.css("width","200px");
}, 1000);
}).mouseleave(function() {
clearTimeout(myTimeout);
el.css("width","100px");
});

jQuery Div Toggle Issue

Live site- http://www.arif-khan.net/other/toggle.html
Red bar on the left side is a switch to toggle a div. My problem is when you click it for first time it doesn't work, subsequent clicks it behaves as expected. I'm pretty sure that is because first time it hide div then show div. I need to fix that, so on first click it show corresponding div instead of hide it.
Code-
<script>
var speed = 300;
$('#close-bar').on('click', function(){
var $$ = $(this);
if( $$.is('.hide-bar') ){
$('#toggleBox').animate({left:-212}, speed);
$$.removeClass('hide-bar')
} else {
$('#toggleBox').animate({left:0}, speed);
$$.addClass('hide-bar')
}
});
</script>
var speed = 300;
$('#close-bar').on('click', function () {
if ($(this).hasClass('hide-bar')) {
$('#toggleBox').animate({left:0}, speed);
$(this).removeClass('hide-bar');
} else {
$('#toggleBox').animate({left:-212}, speed);
$(this).addClass('hide-bar');
}
});
DEMO
Could try removing the is portion and replacing with hasClass (http://api.jquery.com/hasclass/)
if($$.hasClass('hide-bar')){
}else{
}

How do I change images every 6 seconds? [duplicate]

This question already has an answer here:
How can I execute javascript code every a specific time interval?
(1 answer)
Closed 9 years ago.
How do I add an interval to the below code so it does it change images automatically every 6 seconds?
I use this code from fearlessflyer.com
$(window).load(function () {
var theImage = $('ul li img');
var theWidth = theImage.width();
//wrap into mother div
$('ul').wrap('<div id="mother" />');
//assign height width and overflow hidden to mother
$('#mother').css({
width: function () {
return theWidth;
},
height: function () {
return theImage.height();
},
position: 'relative',
overflow: 'hidden'
});
//get total of image sizes and set as width for ul
var totalWidth = theImage.length * theWidth;
$('ul').css({
width: function () {
return totalWidth;
}
});
$(theImage).each(function (intIndex) {
$(this).nextAll('a')
.bind("click", function () {
if ($(this).is(".next")) {
$(this).parent('li').parent('ul').animate({
"margin-left": (-(intIndex + 1) * theWidth)
}, 1000)
} else if ($(this).is(".previous")) {
$(this).parent('li').parent('ul').animate({
"margin-left": (-(intIndex - 1) * theWidth)
}, 1000)
} else if ($(this).is(".startover")) {
$(this).parent('li').parent('ul').animate({
"margin-left": (0)
}, 1000)
}
}); //close .bind()
}); //close .each()
}); //doc ready
Here is an extended answer
var intNum = 6000; //repeat every 6 seconds
function startInterval(){
window.int = setInterval(function(){
//code to move to next image
},intNum);
}
That will set the interval for the image, going to the next automatically, small adjustments might be needed when comparing to your click event for the switch, so I left the inside blank.
the function startInterval() should be called when you know that the rest of the code is loaded and ready (click events are set, ect).
When you do a click event to manually switch back and forth you want to use the following
clearInterval(int);
//code to switch image from click
startInterval();
You need to use the setInterval() function.
Basically, it would look something like:
var currentImg=0;//Current image tracker
var imgList["img1.jpg","img2.jpg","img3.jpg"];//Image names
var changeImage = function(){
//Change src attribute on img element
$('ul li img').attr('src','/imgdir/'+imgList[currentImg]);
if(currentImg>=imgList.length-1)//Check if current image is the last in the list
currentImg=0;//Sets to first images if true
else
currentImg++;//Sets to next image if false
}
//Sets an interval of 6000ms on the window object that calls the function changeImage()
//on every trigger
window.setInterval(changeImage(),6000);
MDN Reference
Hope this helps, I'd suggest checking out the jQuery Documentation aswell...
Use the setInterval() javascript function, as explained here.

Fading Latest News Ticker

I'm looking to get the most efficient way to produce a latest news ticker.
I have a ul which can hold any number of li's and all I need to to loop through them fading one in, holding it for 5 seconds and then fading it out, one li at a time. The list is displaying with an li height of 40px and the well it displays in is also 40px which with overflow: hidden which produces the desired effect. Also to be able to hold the li in place if the cursor hovers over it while its being displayed would be great to build it.
I know there is the jQuery ticker plugin that is widely used (ala the old BBC style) but I've tried to use it and it seems so bulky for the simplicity I need and it plays havoc with the styling I use.
I've been using this so far:
function tickOut(){
$('#ticker li:first').animate({'opacity':0}, 1000, function () {
$(this).appendTo($('#ticker')).css('opacity', 1); });
}
setInterval(function(){ tickOut () }, 5500);
But it doesn't actually fade in the next li so the effect is a bit messy.
If someone could suggest some alternations to help produce the effect I need that would be so useful.
Thanks
hide() and call fadein() the element after it becomes the top of the list.
function tickOut(){
$('#ticker li:first').animate({'opacity':0}, 1000, function () {
$(this).appendTo($('#ticker'))
$('#ticker li:first').hide()
$('#ticker li:first').fadeIn(1000)
$('#ticker li:not(:first)').css('opacity', '1')
});
}
setInterval(function(){ tickOut () }, 5500);
see:
http://codepen.io/anon/pen/lHdGb
I woudl do it like that:
function tickOut(){
$('#ticker li:first').animate({'opacity':0}, 1000, function () {
$(this).appendTo($('#ticker')).css('opacity', 1); });
}
var interval;
$(function() {
interval = setInterval(function(){ tickOut () }, 5500);
$('#ticker').hover(function() {
if(interval)
clearInterval(interval);
$('#ticker li:first').stop();
$('#ticker li:first').css('opacity', 1).stop();
}, function(){
interval = setInterval(function(){ tickOut () }, 5500);
});
});
See $('#ticker').hover which clears interval and stops animation and returns opacity to 1 when mouse got inside UL (may be changed to do that when only some special element inside LI is under mouse) and starts it again once it left that UL. Demo: http://jsfiddle.net/KFyzq/6/

JS/jQuery - Try to achieve show a div on and off use mouseenter() mouseleave() so not to get repeated animations

So here's my code:
var timeouts = {};
$('#nav ul > li').mouseenter(function() {
clearTimeout(timeouts['menu']);
$(this).find('div.dropdown').stop(true).slideDown(200);
});
$('#nav ul > li').mouseleave(function() {
timeouts['menu'] = setTimeout(function() {
$(this).find('div.dropdown').stop(true).slideUp(200);
}, 1000)
});
This doesn't seem to be working. Any idea?
Is there any other way to achieve my goal? The code now works when I hover my mouse over but the div will not slide up when my mouse leaves.
Inside of your anonymous function, this is probably not defined as a HTML element.
Put this in the proper scope:
var timeouts = {'menu': false};
$('#nav ul > li').hover(function() {
if (timeouts['menu'] !== false) {
clearTimeout(timeouts['menu']);
}
$(this).find('div.dropdown').stop(true).slideDown(200);
}, function() {
var $this = $(this);
timeouts['menu'] = setTimeout(function() {
$this.find('div.dropdown').stop(true).slideUp(200);
}, 1000)
});
Also, you're probably going to get an error if you try to call timeouts['menu'] without it being defined first. I'd set it to a default value and then check if it exists before using it.
You could try the hoverIntent plugin or have a look at some of the solutions here: jQuery if mouse is over for 2 sec. begin animation or don't animate at all

Categories

Resources