The HTML structure is like this
<ul class="innerfade">
<li style="position: absolute; z-index: 4; display: none;">some Text</li>
<li style="position: absolute; z-index: 3; display: none;">bla bla bla</li>
<li style="position: absolute; z-index: 2; display: none;">bla bla</li>
<li style="position: absolute; z-index: 1; display: none;">some Text</li>
<ul>
I wanna change the css of each <li> from display:none to display:block to none again after an interval. And this goes on in an endless loop. Can someone tell me how to acheive this in jquery.
So far my Jquery look like this -
$('.innerfade li').each(function()
{
$(this).css('display', 'block');
$(this).fadeOut('slow');
});
I tested this on firebug console but it didn't work. And i didnt go ahead and add the setTimout function.
Anyway any Help will be greatly appreciated!
Edit: I have edited the code so i can explain better what i'm trying to acheive. Like you can see each li is one below the other. The li's contain pictures and some text in the same structure(which i have omitted from here to keep things simple). Hence i want only one li to display at a time and then fade out. N then the next li takes over n so on and so forth in an endless loop. And i want each li to stay alive for roughly 5 mins
DEMO
var el = $('.innerfade li'),
i = 0;
$(el[0]).show();
(function loop() {
el.delay(1000).fadeOut(300).eq(++i%el.length).fadeIn(500, loop);
}());
Edit:
This code was written way too late at night by a tired programmer (myself), and should not be used due to browser hosing. Please see jQuery draws to a halt on Chrome and mac OS for production-quality code!
Do not use the below code.
Use two mutually-dependent functions:
var $lis = $('ul.innerfade > li');
function fadeThemOut()
{
$lis.fadeOut('slow', fadeThemIn);
}
function fadeThemIn()
{
$lis.fadeIn('slow', fadeThemOut);
}
// kick it off
fadeThemOut();
Demo: http://jsfiddle.net/mattball/nWWSa/
You can write this more concisely using .fadeToggle():
var $lis = $('ul.innerfade > li');
function toggleThem()
{
$lis.fadeToggle('slow', toggleThem);
}
// kick it off
toggleThem();
Demo: http://jsfiddle.net/mattball/XdAEG/
Try this
setInterval(function(){
$(".innerfade li").fadeToggle();
}, 1000);
Edit: Based on your clarification of what you are trying to achieve:
(function () {
var i = 0;
var delay = 1000 * 60 * 5; // 5 minutes
var items = $(".innerfade li");
var len = items.length;
setInterval(function () {
items.fadeOut().eq(++i % len).fadeIn();
}, delay);
})();
The above gives you a cross-fade effect. If you want to completely fade out before fading in the next element, you want this:
(function () {
var i = 0;
var delay = 1000 * 60 * 5; // 5 minutes
var items = $(".innerfade li");
items.eq(0).show();
var len = items.length;
setInterval(function () {
items.filter(":visible").fadeOut(function() {
items.eq(++i % len).fadeIn();
});
}, delay);
})();
http://jsfiddle.net/gilly3/CDHJY/
jQuery uses CSS-Selectors. What you are doing is trying to get all li-tags inside an innerfade-tag, which obviously doesn't exist.
You need to select it using its class, just like in CSS:
$(".innerface li")...
Although not fit with your Endless Loopm but this is a Loop where you stop at the Endpoint
var el = $('.innerfade li'), i = 0; $(el[0]).fadeIn();<BR> (function loop() { if(i+1<4){ el.delay(1000).fadeOut(300).eq(++i%el.length).fadeIn(500, loop);<BR>} else el.delay(1500).fadeOut(1000); <BR>} ());
try this:
$(function() {
$('.innerfade li').each(function() {
blink($(this))
});
});
function blink(li) {
li.fadeOut('slow', function() {
li.fadeIn('slow', blink(li));
});
}
Check out this fiddle.
Related
I am making a HTML5 banner and need to loop through 3 overlapping banners.
The script I'm currently using looks like this:
var currentDelay; currentDelay = 0;
var pastItem; pastItem = "";
$( ".state" ).each(function() {
$(this).delay(currentDelay).fadeIn();
$(this).prev().delay(3000).fadeOut();
currentDelay += 3000;
});
It works, but only works once. .state is the wrapping class for each banner. They are positioned over the top of each other and should fade in and out of each other.
HTML:
<div class="state">
<img src="images/img-1.jpg" alt="Last minute ski holidays from £299pp" />
<div class="message"><p>Last minute<br />ski holidays from £299<span>pp</span></p></div>
</div>
<div class="state">
<img src="images/img-2.jpg" alt="Enjoy free skiing guide & coaching" />
<div class="message blue"><p>Enjoy free<br />skiing guide<br />& coaching</p></div>
</div>
<div class="state">
<img src="images/img-3.jpg" alt="Last minute ski holidays from £299pp" />
<div class="message grey"><p>Limited availability<br /><span class="sub-mes">Don't miss out</span></p></div>
<p class="call-to-action">Find out more</p>
</div>
Is there a way I can make it loop round 3 times then just stop on the last frame? The last banner needs to fade back to the first frame so it looks seamless.
Big thanks for some help on this :)
Cheers
Rob
Here is a method using setInterval.
I have commented the code so I will not bother explaining it.
JS:
$(document).ready(function() {
var currentDelay; currentDelay = 3000;
var pastItem; pastItem = "";
var i=0;
// interval
var cycle = setInterval(function() {
// Fade
$(".state:eq(" + i + ")").fadeOut();
// Increment
i++;
// Increase delay
currentDelay+=3000;
// Check if at last, change to suit wants
if(i == $(".state").length) {
/*
// Loop here
$(".state").delay(500).fadeIn();
i=0;
*/
// Stop interval
clearInterval(cycle); // Comment this line if looping
}
}, currentDelay);
})
Fiddle: https: https://jsfiddle.net/4bhv9w80/1/
You can do this with a self-referencing function that calls its self 3 times.
var sleepTimer = 0;
(function LoopyLoo(i) {
setTimeout(function() {
var currentDelay = 0
$(".state").fadeOut();
$(".state").each(function() {
$(this).delay(currentDelay).fadeIn();
currentDelay += 3000;
});
if (--i) {
LoopyLoo(i);
}// decrement i and call myLoop again if i > 0
}, sleepTimer)
sleepTimer = 9000;
})(3); //Times to call the function.
Small change to the css, added some lovely colour so you can see it in action.
.state-con {
position: relative;
}
.state {
display: none;
position: absolute;
top: 0;
left: 0;
}
.one {
z-index: 1;
background-color: red;
}
.two {
z-index: 2;
background-color: blue;
}
.three {
z-index: 3;
background-color: aqua;
}
See it all working with this JS fiddle.
https://jsfiddle.net/yojmu6ga/21/
Hope this works for you:
var currentDelay; currentDelay = 0;
$( ".state" ).each(function() {
var $currentElement =$(this);
window.setTimeout(function(){
$( ".state:visible" ).fadeOut();
$currentElement.fadeIn();
}, currentDelay);
currentDelay += 3000
});
window.setTimeout(function(){
$( ".state:visible" ).fadeOut();
$(".state:first").fadeIn();
}, currentDelay);
https://jsfiddle.net/2k6c1b18/
I am making an info screen, and for that, it needs to show reviews from their customers pulled from Trustpilot.
I got the reviews and everything formatted in HTML showing the 20 latest, but I want to present it very sweet. I am not a JavaScript guru, but I thought i would do it using jQuery and its fadein function.
What is want, is have 20 unique divs fading in with X milliseconds difference popping randomly up. By unique I mean, that each div must have unique content. And by randomly popping up, I mean that if box 1 spawns first, then the next should be 5, then 14 etc, and then another cycle the next time around.
Just like what I made here;
$(function() {
var box = $('.box');
var delay = 100;
for (i = 0; i < 30; i++) {
setTimeout(function() {
var new_box = box.clone();
$('.container').append(new_box);
new_box.fadeIn();
}, delay);
delay += 500; // Delay the next box by an extra 500ms
}
});
http://jsfiddle.net/CCawh/5/
Is this even possible, and how would this be done?
I am very new to JavaScript, so please bear with me if I ask to much
Thanks in advance.
EDIT:
The HTML i want to spawn will all be wrapped in divs, so it would go like this;
<div id="one">content</div>
<div id="two">content</div>
<div id="three">content</div>
<div id="four">content</div>
etc.
Made up a nice function for you. I believe this may be what you are looking for
Here's a rundown of how it works :
Populate an array with numbers randomly generated 1-10 in this case.
Run through that array with a set interval, and when everything has
been added stop the interval
pretty straightforward from there. Set the visibility etc. You should be able to change up the function to dynamically add HTML elements and what-not, but just giving you something to start with.
var usedNum = [];
var i, j, y;
i = 0;
for(y = 0; y < 10; y++){
var x = Math.floor((Math.random() * 10) + 1);
if(!isUsed(x)) usedNum.push(x);
else y--;
}
var showInterval = setInterval ( function(){
if(i == 10){
clearInterval(showInterval);
}
$(".container div[data-line='" + usedNum[i] + "']").css({opacity: 0.0, visibility: "visible"}).animate({opacity: 1.0});
i++;
}, 500);
function isUsed(num) {
var used = false;
for(j = 0; j < usedNum.length; j++){
if(usedNum[j] == num){
used = true;
}
}
return used;
}
Demo fiddle : http://jsfiddle.net/xS39F/3/
Edit:
You can also mess around with the speed of the animation. In this demo (http://jsfiddle.net/adjit/XYU34/1/) I set the speed to 1000 so the next element starts fading in before the last element was done fading in. Makes it look a little smoother.
Instead of using a for loop and setTimeout, would setInterval work better for what you need? Some HTML might help better understand what you're trying to achieve.
$(function() {
var box = $('.box');
var delay = 100;
var interval = setInterval(function() {
var new_box = box.clone();
$('.container').append(new_box);
new_box.fadeIn();
}, delay);
delay += 500; // Delay the next box by an extra 500ms
}, delay);
});
Im trying to make a 'blanket' of divs containing child divs 150px high and 150px wide.
I want each child div to fade in 1 after the other after after a millisecond or so, opacity changing from 0, to 1.
I cant seem to figure out how this works, or how id do it though?
http://jsfiddle.net/CCawh/
JS
$(function(){
var figure = [];
w = 1500;
h = 450;
for(i = 0, i < 30, i++){
$('div').append(figure[].clone()).fadeIn();
}
});
Here is a working solution.
The problems in your code
in for(i = 0, i < 30, i++), you should use ';', not ',' . Use developer tools in your browser to catch such typos
In your code $('div').append(figure[].clone()).fadeIn(); , The fadeIn applies to $('div') as append() returns the calling object itself. You must replace it with $('<figure></figure>').appendTo('div').fadeIn('slow'); and to fadeIn items one by one you could set a timeout with incrementing delays
Add display: none; style to the figure to keep it hidden initially
Here is the full code.
$(function(){
for(i = 0; i < 30; i++){
setTimeout(function(){$('<figure></figure>').appendTo('div').fadeIn('slow');}, i*200);
}
});
Here is a fiddle to see it working http://jsfiddle.net/CCawh/12/
Try using greensock TweenLite http://www.greensock.com/get-started-js/.
It has staggerTo/staggerFrom action that does exactly what you are asking. TweenLite in conjunction with jQuery makes animation very easy.
This would be a possible solution (DEMO).
Use an immediate function and call it again n times in the fadeIn callback.
$(function(){
var figure = $('figure');
var counter = 0;
(function nextFade() {
counter++;
figure.clone().appendTo('div').hide().fadeIn(500, function() {
if(counter < 30) nextFade();
});
})();
});
You can use the following implementation as an example. Using setTimeout() will do the trick.
I've updated your jsfiddle here: http://jsfiddle.net/CCawh/5/
HTML:
<div class="container">
<div class="box"></div>
</div>
CSS:
.box {
display: none;
float: left;
margin: 10px;
width: 150px;
height: 150px;
background-color: #000;
}
JS:
$(function() {
var box = $('.box');
var delay = 100;
for (i = 0; i < 30; i++) {
setTimeout(function() {
var new_box = box.clone();
$('.container').append(new_box);
new_box.fadeIn();
}, delay);
delay += 500; // Delay the next box by an extra 500ms
}
});
Note that in order for the element to actually fade in, it must be hidden in the first place, i.e. display: none; or .hide()
Here's perhaps a more robust solution without counters:
http://jsfiddle.net/CCawh/6/
for(var i = 0; i < 30; i++){
$('div').append($('<figure>figure</figure>'));
}
(function fade(figure, duration) {
if (figure)
figure.fadeIn(duration, function() { fade(figure.next(), duration); });
})($('figure').first(), 400);
By the way, clauses in for loops are separated using semicolons, not commas.
Hey all, I'm new to JavaScript and I'm using the jQuery library for this.
Basically I'm trying to create multiples of this line and I'm using ":eq(0) to do it.
The issue is that :eq(0) repeats 3 times in the code and with the loop that I'm doing every time it repeats it has a different number.
This is what I'm getting from it i think (:eq(0), :eq(1),:eq(2), :eq(3), etc..)
I need it to do this (:eq(0),:eq(0),:eq(0), :eq(1) :eq(1) :eq(1), etc...)
for (i = 0; i < 6; ++i) {
var $titleMarquee = '<marquee scrollamount="5" direction="left" width="233" align="left" behavior="alternate" loop="1"><span>';
var $lieq = "li:eq("+i+")";
$("ul.side-block-content "+$lieq+"").mouseenter(function() {
$("ul.side-block-content "+$lieq+" .article-title a span")
.replaceWith($titleMarquee+$("ul.side-block-content "+$lieq+" .article-title a").text()+"</span></marquee>");
});
}
If anyone can let me know how to do this loop correctly, or maybe how to recreate the code for it to do the same thing that would be great.
Thanks in advance.
#Nick's answer:
var $titleMarquee = '<marquee scrollamount="5" direction="left" width="233" align="left" behavior="alternate" loop="1"><span>';
for (i = 0; i < 6; ++i) {
for (j = 0; j < 7; ++j) {
$("ul.side-block-content li:eq("+i+")").mouseenter(function(){$("ul.side-block-content li:eq("+i+") .article-title a span").replaceWith($titleMarquee+$("ul.side-block-content li:eq("+i+") .article-title a").text()+"</span></marquee>");});
$("ul.side-block-content li:eq("+i+")").mouseleave(function(){$("ul.side-block-content li:eq("+i+") .article-title a marquee").replaceWith('<span>'+$("ul.side-block-content li:eq("+i+") .article-title a").text()+"</span>");});
}
}
This is what I'm using now and it's not working. Am I doing it correctly?
#Gilly3
$("ul.side-block-content li marquee").each(function() {
this.stop(); // prevent the marquee from scrolling initially
}).mouseenter(function() {
this.start(); // start the scroll onmouseenter
});
<marquee scrollamount="5" direction="left" width="233" align="left" behavior="alternate">
It looks like you are trying to make your <li> text scroll when you hover over it. Is that right?
Just put the marquee code in the original html and do this:
$(function ()
{
$("ul.side-block-content li marquee").each(function() {
this.stop(); // prevent the marquee from scrolling initially
}).mouseenter(function() {
this.start(); // start the scroll onmouseenter
});
});
I also want to say not to use the marquee tag since it is deprecated and to use a jQuery plugin instead, but the last jQuery marquee plugin I saw was actually using a <marquee> in the back end anyway. So... pfft.
You could embed another for loop inside, like so:
for (i = 0; i < 6; ++i) {
for (j = 0; j < 3; ++j) {
// repeat i three times, and use :eq("+i+")
}
}
For one of my first ventures into JQuery, I have the very simple goal of stepping through the children of a div and fading them in and out one by one. For some reason though, if I manually define an index for nth-child, say 1, then the first child fades in and out four times. If I use the variable "i", however, then all of the children fade in and out four times. Why is this happening?
Here is my code:
<div id="slideshow">
<p>Text1</p>
<p>Text2</p>
<p>Test3</p>
<p>Text4</p>
</div>
<script>
$(document).ready(function() {
var $elements = $('#slideshow').children();
var len = $elements.length;
var i = 1;
for (i=1;i<=len;i++)
{
$("#slideshow p:nth-child(i)").fadeIn("slow").delay(800).fadeOut("slow");
}
});
</script>
Each of the paragraphs is set to display: none; initially.
You need to escape i. Right now, nth-child is looking for the child that has an index of i, not of 0, 1, 2, etc. So instead, use:
$('#slideshow p:nth-child(' + i + ')').fadeIn('slow').delay(800).fadeOut('slow');
However, I don't think that will do one at a time; in fact, I'm pretty sure it won't. If it doesn't, try something like this:
var delay = 0;
$('#slideshow p').each(
function (index, item)
{
$(this).delay(delay).fadeIn('slow').delay(800).fadeOut('slow');
delay += 2200;
}
);
That's untested, but should be decent pseudocode at the very least.
When you manually enter a index (1), then you loop 4 times and fadein the first child 4 times.
When you use i they will all fadeIn four times since i inside a string is not a reference to the i variable, it's just part of the string.
$(document).ready(function() {
var $elements = $('#slideshow').children();
var len = $elements.length;
var i = 1;
for (i=1;i<=len;i++)
{
$("#slideshow p:nth-child("+i+")").fadeIn("slow").delay(800).fadeOut("slow");
}
});
Should work, notice "+i+"
A better way to do this is:
$(function(){
$('#slideshow p').each(function(i, node){
setTimeout(function(){
$(node).fadeIn("slow").delay(800).fadeOut("slow");
node = null; //prevent memory leak
}, i * 800);
});
});
I am not saying this impossible but in the end it will be pointless to use even if you get it to work, as it will fail on IE.
refer here.
http://css-tricks.com/how-nth-child-works/