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

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.

Related

jQuery create interval within each cant access $(this)

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

Click handler is called multiple times in jQuery animate

I am getting familiar with jQuery and making a little application where a red box moves around the screen and the user has to try and click on it and when the user does an alert() box pops up but the problem is that the alert() keeps popping up even after 'ok' is pressed. The only way I can stop it is to repeatedly click 'ok' and eventually it goes away.
Here is the code that displays the alert box:
function Animate() {
var _newPosition = GetNewPosition();
// Sets new position of div
div.animate({
top: _newPosition[0],
left: _newPosition[1]
}, function () {
div.on('click', function () {
alert('You clicked the box!');
});
Animate();
});
}
Here is my JSFiddle that reproduces the problem
I originally thought that I could solve it by returning false after the call to the alert() for example:
div.on('click', function () {
alert('You clicked the box!');
return false;
});
But that didn't work either.
I know this should be a simple thing to figure out but I cant quite seem to get my thumb on it.
The click handler is recursively called in the animation complete callback which is binding the click event on the element multiple times. So, when the element is clicked the handler is being called multiple times.
To solve the issue, bind the event only once.
function Animate() {
var _newPosition = GetNewPosition();
// Sets new position of div
div.animate({
top: _newPosition[0],
left: _newPosition[1]
}, Animate);
}
And in ready()
$(document).ready(function () {
Animate();
div.on('click', function() {
// Code here
alert('clicked');
});
});
Using Animate as reference to the animation complete callback is same as
function() {
Animate();
}
The function reference will be passed to the animate and it'll be called when the animation is completed.
Suggestions:
Use mousedown event to track the click on moving object
Use random duration for animate.
FIddle
var div = $('#box');
$(document).ready(function() {
Animate();
div.on('mousedown', function() {
// Code here
console.log('clicked');
});
});
function GetNewPosition() {
// Get dimentions of the window and remove the div area
var h = $(window).height() - 50;
var w = $(window).width() - 50;
// New height and width is auto generated
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh, nw];
}
function Animate() {
var _newPosition = GetNewPosition();
// Sets new position of div
div.animate({
top: _newPosition[0],
left: _newPosition[1]
}, (Math.floor(Math.random() * 5000) + 1), Animate);
}
#box {
width: 50px;
height: 50px;
background-color: red;
position: fixed;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3 id="success"></h3>
<div id="box"></div>
Event is getting bound multiple times as it is in animate function. Instead binding click event in animate bind it in $(document).ready(function () {}); so that it will only get bound once.
Please find updated jsfiddle

Submenu animation "pops up"

I have a menu with sub items inside it. In order to make animation effect I want, I need to retrieve sub-menu width,height and height of its first-child. Now my animation works ,but sometimes my sub-menu just "pops up" (it doesn't animate its width ).
Here is The Fiddle of the problem.
http://www.vasinternetposao.com/wordpressdevelopment/wp-content/themes/override/images/submenu_problem.png
I am using this code:
var j = jQuery.noConflict();
j(document).ready(function () {
j('ul.nav').removeClass('nav').addClass('jnav'); //Add jquery Class to our menu
j('ul.jnav li').hover(function () {
if (j(this).children('ul:first').hasClass('jsub-menu')) { //Let's check if "jsub-menu" Class is here
return false; //If it is ("jsub-menu" here) don't SlideDown...
} else { //Else slide down if no class
j(this).find('ul.sub-menu:first').not(':animated').slideDown(500);
}
}, function () {
j(this).find('ul:first').slideUp(500, function () {
j(this).removeClass('jsub-menu').addClass('sub-menu');
j(this).css({
'height': '',
'width': ''
});
});
});
j('ul.jnav ul.sub-menu a').hover(function () {
j(this).addClass('active');
if (j('.active').next('ul.sub-menu').length) { //If submenu exist...
j('.active').next('ul.sub-menu').css({
'visibility': 'hidden',
'opacity': '0',
'display': 'block'
}); //Show it so we can read its:
var get_width = j('.active').next('ul.sub-menu').outerWidth(true); //WIDTH
var get_height_of_first_child = j('.active').next('ul.sub-menu').children('li:first').outerHeight(true); //HEIGHT of its First Child
var get_submenu_height = j('.active').next('ul.sub-menu').outerHeight(true); //HEIGHT of our menu
j('.active').next('ul').removeClass('sub-menu') //Remove class from menu, add another class apply HEIGHT of FIRST CHILD and hide it again...
.addClass('jsub-menu').css({
'visibility': '',
'opacity': '',
'height': get_height_of_first_child + 'px',
'width': '0'
});
j('.active').next('.jsub-menu').animate({
width: get_width
}, 1000, function () { //Animate WIDTH
j('.active').next('.jsub-menu').animate({
height: get_submenu_height
}, 1000); //callback animate HEIGHT
});
} //End if
}, function () {
j('.active').removeClass('active');
});
});
I think that this is happening because my Slide Up/Down animations are conflicting with my animate with/height functions but I am not sure. I have tried to solve it by adding stop(),stop(true,true),stop(true,false) in numerous combinations but failed. I am trying to solve this for days now so you stackers are my only hope. Please help!
Thank you!!
I was finally able to replicate the error.
I wrote this code for you, to replace the code you have for the animation.
var animating = false;
function animate($elm, options, callback) {
if (animating)
return;
animating = true;
$elm.animate(options, 1000, function() {
animating = false;
if (callback != undefined)
callback();
});
}
Call it like this, from inside your hover callback.
animate(j('.active').next('.jsub-menu'),
{
'width': get_width,
'height' : get_submenu_height
});
Basically, it checks if another animation is already running, in which case it doesn't start it. The Flag is set to false when the animation stopped, and let's other animations go on.
You can also pass a callback to do something after the animation is completed, but in your case you don't need it, because you can animate the height and width in the same time.
I tested it for like a minute and it looked pretty smooth.
Here is the updated feedle: http://jsfiddle.net/gabrielcatalin/TNxJ4/1/
P.S. You may also want to use the $ sign instead of 'j' for jQuery wrappers.

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/

finish animation before starting another

Problem: Whenever I click faster or slower I need last .click() call to finish before the next one starts. If you click the button faster , in the given example, you can see it's leaving divisions with 0 opacity.
What I want to achieve is stacking up till 3-4. I tried some queue code examples, couldn't make it work.
$("#addNew").click(function(){
var _this = $("#scrollable");
//Switch classes
_this.find("div.first").switchClass("first","second",500);
_this.find("div.second").switchClass("second","third",500);
_this.find("div.third").switchClass("third","fourth",500);
_this.find("div.fourth").switchClass("fourth","fifth",500);
// Insert first/new line
$("<div class='first'>Hello!</div>").css("opacity","0").hide().prependTo(_this).slideDown(function(){$(this).stop().animate({opacity:1},300)})
$("div.fifth").fadeOut().remove();
});
Here is example: http://jsfiddle.net/gtFyP/5/
Use setInterval
You could combine the below flag solution with setInterval, and thus be able to process clicks occurring during an animation.
Updated your JS Fiddle again with this alternate solution.
$(function() {
var clicking = false;
var clickCache = 0;
window.setInterval(function(){
if (!clicking && clickCache) {
processClick();
clickCache--;
}
}, 100);
var processClick = function() {
var _this = $("#scrollable");
//Switch classes
_this.find("div.first").switchClass("first", "second", 500);
_this.find("div.second").switchClass("second", "third", 500);
_this.find("div.third").switchClass("third", "fourth", 500);
_this.find("div.fourth").switchClass("fourth", "fifth", 500);
clicking = true;
// Insert first/new line
$("<div class='first'>Hello!</div>").css("opacity", "0").hide().prependTo(_this).slideDown(function() {
$(this).stop().animate({
opacity: 1
}, 300, function(){
clicking = false;
});
});
$("div.fifth").fadeOut().remove();
};
$("#addNew").click(function() {
clickCache++;
});
});
Use a Flag
You could use a flag - only start an animation if it's false. When you start animating, set it to true, when the animation is done, set it back to false.
I've modified your JS Fiddle.

Categories

Resources