JavaScript (jQuery) for-loop question - javascript

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+")
}
}

Related

adding fade to slide script?

I was wondering if someone could help me, is there a way to add fade betwene slides in this preticular script code? It targets buttons that changes images. Thanks upfront!
<script>
var slideIndex1 = 1;
showDivs1(slideIndex1);
function plusDivs1(n) {
showDivs1(slideIndex1 += n);
}
function showDivs1(n) {
var i;
var y = document.getElementsByClassName("mySlides1");
if (n > y.length) {
slideIndex1 = 1
}
if (n < 1) {
slideIndex1 = y.length
}
for (i = 0; i < y.length; i++) {
y[i].style.display = "none";
}
y[slideIndex1 - 1].style.display = "block";
}
</script>
I believe that what you are looking to achieve is a carousel (Bootstrap example)
Instead of applying display="none" to all these elements, if I were you I would toggle some CSS class which uses an animation or a transition .
You can learn more about CSS animations here (just an example of what you can achieve with vanilla CSS)
It can be tedious to create a working and responsive carousel, hence I would suggest you either to use a premade solution, or use an util library such as jQuery, which provides plenty of animations.

jQuery fade in box with unique content

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

Fade in boxes 1 after the other with jQuery

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.

Create an endless loop in Jquery

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.

fadeIn fadeOut effect with Raw javascript

I am currently working on a experiment with RAW Javascript. I was wondering why it is not working. In fact I have scratched my head until there is no hair left... :P.
I am making a table with TR elements to be hovered over with some Javascript event. I think you will know exactly what I mean if you look at the code. The point is to get stuff to fade out first and then fade in afterwards when it reaches zero.
I am a beginner and maybe this can be done with the existing code. But of course if it is possible in another way of programming, I am open for suggestions.
THE CODE:
window.onload = changeColor;
var tableCells = document.getElementsByTagName("td");
function changeColor() {
for(var i = 0; i < tableCells.length; i++) {
var tableCell = tableCells[i];
createMouseOutFunction(tableCell, i);
createMouseOverFunction(tableCell, i);
}
}
function createMouseOverFunction(tableCell, i) {
tableCell.onmouseover = function() {
tableCell.style.opacity = 1;
createMouseOutFunction(tableCell, i);
}
}
function createMouseOutFunction(tableCell, i) {
var OpacitySpeed = .03;
var intervalSpeed = 10;
tableCell.onmouseout = function() {
tableCell.style.opacity = 1;
var fadeOut = setInterval(function() {
if(tableCell.style.opacity > 0) {
tableCell.style.opacity -= OpacitySpeed;
} else if (tableCell.style.opacity <= 0) {
clearInterval(fadeOut);
}
}, intervalSpeed);
var fadeIn = setInterval(function(){
if(tableCell.style.opacity <= 0){
tableCell.style.opacity += OpacitySpeed;
} else if(tableCell.style.opacity == 1){
clearInterval(fadeIn);
}
}, intervalSpeed);
}
}
Here is working example of your code (with some corrections)
http://www.jsfiddle.net/gaby/yVKud/
corrections include
Start the fadein once the fadeout is completed (right after you clear the fadeout)
ues the parseFloat() method, because the code failed when it reached negative values.
remove the createMouseOutFunction(tableCell, i); from the createMouseOverFunction because you assign it in the initial loop.
I think you'll probably need to use the this keyword in some of your event binding functions. However I haven't myself got your code to work.
I would recommend using a library such as jQuery. In particular .animate will probably be of use here.

Categories