How to Iterate with fade out? - javascript

I wanna to improve this chunk of code to make each image appears independently and doing the fade out.
This one face a problem , which is iterating quickly , so only the last image is appeared and doing the fade out.
jQuery.each(
slidesArray, function (index, value) {
var linkHref = value[1];
var imageSource = value[0];;
$("#slider").html("<a href='" + linkHref + "'><img src='" +
imageSource + "'></a>").fadeOut(5000);
});
Can you help me ? note that images should be animated respectively.

Here's a little jQuery plugin that will help:
jQuery.slowEach = function( array, interval, callback ) {
if( ! array.length ) return;
var i = 0;
next();
function next() {
if( callback.call( array[i], i, array[i] ) !== false )
if( ++i < array.length )
setTimeout( next, interval );
}
};
jQuery.fn.slowEach = function( interval, callback ) {
jQuery.slowEach( this, interval, callback );
};
Include the plugin above. It adds a slowEach method and function: $(...).slowEach(interval,callback) and $.slowEach(interval,delay,callback). It iterates over an object or jQuery selection, waiting for delay milliseconds after each iteration.
Edit your code from above to use slowEach:
jQuery.slowEach(
slidesArray, 5000, function (index, value) {
var linkHref = value[1];
var imageSource = value[0];
$("#slider").html("<a href='" + linkHref + "'><img src='" + imageSource + "'></a>").fadeOut(5000);
});

I haven't tested this, but in theory should work
function fader(i){
$("#slider").css('display', '');
if (i == slidesArray.length){
return;
}
var linkHref = slidesArray[i][1];
var imageSource = slidesArray[i][0];
i++;
$("#slider").html("<a href='" + linkHref + "'><img src='" +
imageSource + "'></a>").fadeOut(5000, fader(i));
}
fader(0);
Edit: I've tested it, seems to be working. Here's a similar use demo
Notice that there's no need to use setTimeout

Every time you call $("#slider").html() you replace the content of #slider.
what you want to do isn't delay the actual loop, you want to delay the placement [and fading] of the image. You can use setTimeout to do that like this:
jQuery.each
(
slidesArray,function(index,value)
{
var linkHref = value[1];
var imageSource = value[0];;
setTimeout(function() {
$("#slider").html
(
"<a href='" + linkHref + "'><img src='"+ imageSource + "'></a>"
).fadeOut(5000);
}, 2000 * index);
}
);

Related

I'm using jquery and regular javascript on a page with no probs until I added one more function

Here's what I'm doing.
I have a few images on a page with an HTML5 audio player underneath each one and a select menu with a list of sounds.
When a sound is selected from the menu, it places that sound in the source of the audio player.
What I want to do is change the image to an animated gif when the sound is played.
The onchange works fine loading the sound into the player. But when I add the new onplay() call, none of the javascript works.
function playPic(theid){
var leid = theid.replace('play','');
document.getElementById('leid'+pic).src="images/" + leid ".gif";
}
$( function() {
$( "#sortable" ).sortable();
$( "#sortable" ).disableSelection();
} );
$(document).ready(function() {
$('#sortable').sortable();
//$('<br><br><div id=buttonDiv><button>Get Order of Elements</button></div>').appendTo('body');
//$('button').button().click(function() {
$( "#sendgame" ).submit(function( event ) {
var itemOrder = $('#sortable').sortable("toArray");
var fullOrder = "";
for (var i = 0; i < itemOrder.length; i++) {
newi = i + 1;
//alert("Position: " + i + " ID: " + itemOrder[i]);
fullOrder += newi + " - " + itemOrder[i] + "<br>";
}
//alert (fullOrder);
document.forms["sendgame"].ordre.value = fullOrder;
})
});
function recSon(lename, leson) {
document.forms["sendgame"][lename].value = leson;
}
function loudSon(soundid, leplayer) {
lesound = "";
if(navigator.userAgent.toLowerCase().indexOf('firefox') > -1) {
lesound = soundid + ".ogg";
} else {
lesound = soundid + ".mp3";
}
}
The playPic function is what screws everything up. I've tried it in different places in the code but always the same error :
Uncaught ReferenceError: recSon is not defined
at HTMLSelectElement.onchange (jeuhockeynoir.php?lang=f:481)
onchange # jeuhockeynoir.php?lang=f:481
you're missing a + sign:
document.getElementById('leid'+pic).src="images/" + leid ".gif";
should be
document.getElementById('leid'+pic).src="images/" + leid + ".gif";

How to iterate elements over time in jquery

I'm working on this automated, non-endless slideshow, with dynamically loaded content. Each image has to be acompanied by sound. So far I got dynamic loading of both images and sounds down. But it all happens at once, which it shouldn't. I figured, that setTimeout can come in handy here, to set the interval between each pair, but all I got is either last image multiplied by the iteration count or script not working at all. delay also didn't prove to be of any help.
Here's whot I got so far:
function displayImages(data){
var count = data;
var pixBox = $('#picture-box');
var imgPre = 'resources/exhibit-';
var imgExt = '.png';
var sndExt = '.wav';
for(i = 1; i < count; i++) {
var imgSrc = '<img src="' + imgPre + i + imgExt + '">';
var sndSrc = new Audio(imgPre + i + sndExt);
sndSrc.play();
pixBox.append(imgSrc);
}
}
My question is: how to set the setTimeout (or whatever function is the best here), for it to iterate over time. Say, to set the change of img/sound pairs every 2 seconds?
You can use setTimeout like this:
function displayImages(cur, total){
var pixBox = $('#picture-box');
var imgPre = 'resources/exhibit-';
var imgExt = '.png';
var sndExt = '.wav';
var imgSrc = '<img src="' + imgPre + cur + imgExt + '">';
var sndSrc = new Audio(imgPre + cur + sndExt);
sndSrc.play();
pixBox.append(imgSrc);
return setTimeout( 'displayImages(' + ((cur+1)%total) + ',' + total + ')', 2000 );
}
And start it off like this: displayImages(0,total) where total corresponds to your data variable.
The reason I like to use setTimeout and not setInterval in these situations is that setTimeout is only called after the previous function has completed. setInterval can get back-logged and freeze up your page.
Note that the function returns a handle for the timeout. If you should want to stop the animation, you can do this:
var animation = displayImages(0,total);
...some code...
clearTimeout(animation);
and the animation will stop.
You can use a setInterval, this does the same code at every interval.
var myInterval = window.setInterval(displayImages, 2000);
This will make sure your function gets called every 2000 milliseconds.
More information on MDN setInterval
You can try something like this
$(function() {
var count = 100;
var i = 0;
var repeat = setInterval(function() {
if (i <= count) {
var imgSrc = '<img src="' + imgPre + i + imgExt + '">';
var sndSrc = new Audio(imgPre + i + sndExt);
sndSrc.play();
pixBox.append(imgSrc);
i++;
}
else{
i = 0; //reset count if reaches threshold.
}
}, 5000); //5 secs
});
With this, if you want to reset the interval on any event you can simple call
clearInterval(repeat);
See a setInterval example here: JSFiddle
var i = 0;
setInterval(fadeDivs, 3000);
function fadeDivs() {
i = i < images.length ? i : 0;
$('#my-img').fadeOut(200, function(){
$(this).attr('src', images[i]).fadeIn(200);
})
i++;
}

DIV Not Being Generated in IE7 with jQuery

I can't figure out why this script isn't working in IE7 and 8. It works fine in all other browsers, but for some reason, in IE7 and 8 this script is only firing the // thumbs hover bit, and not the // loading images bit (which is actually more important). Everything seems to be fine, does anyone have any ideas?
function featuredJS() {
$("[title]").attr("title", function(i, title) {
$(this).data("title", title).removeAttr("title");
});
// loading images
var last = "featured/01.jpg";
$("#thumbs a").click(function(event) {
event.preventDefault();
var position = $(this).attr("class");
var graphic = $(this).attr("href");
var title = $(this).attr("alt");
var description = $(this).data("title");
var currentMargin = $("#full-wrapper #full").css("marginLeft");
var currentWidth = $("#full-wrapper #full").css("width");
var transitionTest = currentMargin.replace("px", "") * 1;
if(last != graphic && ((transitionTest % 938) == 0 || transitionTest == 0)) {
$("#placeholder").before( "<div class='featured'><div class='description " + position + "'>" + "<h3>" + title + "</h3>" + "<p>" + description + "</p>" + "</div><img src=\"" + graphic + "\" /><div style='clear:both;'></div></div>" );
$("#full-wrapper #full").animate({
marginLeft: "-=938px"
}, 500);
$("#full-wrapper #full").css("width","+=938px");
last = graphic;
};
});
// thumbs hover
$("#thumbs .thumb").hover(
function () {
$(this).find(".red-bar").animate({height:"72px"},{queue:false,duration:500});
},
function () {
$(this).find(".red-bar").animate({height:"3px"},{queue:false,duration:500});
}
);
};
Demo page at http://www.weblinxinc.com/beta/welex/demo/
Your problem is caused by not having a margin set to begin with. transitionTest then becomes NaN because the style is auto, not 0px like you're expecting. Consider trying this instead:
var transitionTest = parseInt("0"+currentMargin,10);
This will trim off the "px" for you, as well as handle the case where the margin is a keyword.

retrieving the twitter search feeds dynamically using ajax

Long back I used JSON and was successful to get the hash tag feeds from twitter and facebook. But presently I am just able to get the feeds but its not being updated constantly that means it not been update dynamically. I guess I need to ajaxify it, but I am not able to do that since I am not aware of ajax. Here is the code which I have used to get the twitter search feeds.
$(document).ready(function()
{
$("#Enter").click(function(event){
var searchTerm = $("#search").val() ;
var baseUrl = "http://search.twitter.com/search.json?q=%23";
$.getJSON(baseUrl + searchTerm + "&rpp=1500&callback=?", function(data)
{
$("#tweets").empty();
if(data.results.length < 1)
$('#tweets').html("No results JOINEVENTUS");
$.each(data.results, function()
{
$('<div align="justify"></div>')
.hide()
.append('<hr> <img src="' + this.profile_image_url + '" width="40px" /> ')
.append('<span><a href="http://www.twitter.com/'
+ this.from_user + '">' + this.from_user
+ '</a> ' + makeLink(this.text) + '</span>')
.appendTo('#tweets')
.fadeIn(800);
});
});
});
});
function makeLink(text)
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
return text.replace(exp,"<a href='$1'>$1</a>");
}
The code below should help you. What I've done is moved the code which fetches the tweets into a function. This function is then called every X seconds to update the box. When the user enters a new search term and clicks "Enter", it will reset the timer.
var fetchSeconds = 30; //Number of seconds between each update
var timeout; //The variable which holds the timeout
$(document).ready(function() {
$("#Enter").click(function(event){
//Clear old timeout
clearTimeout(timeout);
//Fetch initial tweets
fetchTweets();
});
});
function fetchTweets() {
//Setup to fetch every X seconds
timeout = setTimeout('fetchTweets()',(fetchSeconds * 1000));
var searchTerm = $("#search").val();
var baseUrl = "http://search.twitter.com/search.json?q=%23";
$.getJSON(baseUrl + searchTerm + "&rpp=1500&callback=?", function(data) {
$("#tweets").empty();
if (data.results.length < 1) {
$('#tweets').html("No results JOINEVENTUS");
}
$.each(data.results, function() {
$('<div align="justify"></div>').hide()
.append('<hr> <img src="' + this.profile_image_url + '" width="40px" /> ')
.append('<span>' + this.from_user + ' ' + makeLink(this.text) + '</span>')
.appendTo('#tweets')
.fadeIn(800);
});
});
}
function makeLink(text) {
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
return text.replace(exp,"<a href='$1'>$1</a>");
}
Hope this helps

jQuery rotating through list items in a gallery

This has probably been answered before and I already know how this should work, but for some reason it is not. I think it may be how I am looping through the elements.
$(document).ready(function() {
var element = '#gallery ul#gallery-container';
var idx=0;
var timeout = 3000;
var number = $(element + ' li').length;
function changeSlide() {
$(element + ' li:eq(' + idx + ')').fadeOut();
idx = idx + 1;
if (idx == number) {
idx=0;
}
$(element + ' li:eq(' + idx + ')').fadeIn().delay(timeout).delay(0, function() {
changeSlide();
});;
}
$(element + ' li').hide();
$(element + ' li:first').fadeIn().delay(timeout).delay(0, function() {
changeSlide();
});
});
Then the list is like this:
<div id="gallery">
<ul id="gallery-container">
<li><img src="media/images/screen-shot-02.jpg" width="173" height="258" alt=" "></li>
<li><img src="media/images/screen-shot-01.jpg" width="173" height="258" alt=" "></li>
</ul>
</div>
I was trying to get it to loop through the elements one by one, after a delay so the list item calls the function and hides itself, then the counter is incremented and then the current index is shown.
I suspect the culprit to be this as if I put an alert in the function it is called:
$(element + ' li:eq(' + idx + ')').fadeOut();
The main problem is, as the comment states, delay does not do what you think it does - you should be looking at the native setTimeout function instead. In addition to that, there are multiple places where this could be made more efficient. Have a look at this:
var element = $('#gallery-container li'),
length = element.length,
current = 0,
timeout = 3000;
function changeSlide() {
element.eq(current++).fadeOut(300, function(){
if(current === length){
current = 0;
}
element.eq(current).fadeIn(300);
});
setTimeout(changeSlide, timeout);
}
element.slice(1).hide();
setTimeout(changeSlide, timeout);
We try not to evoke the jQuery function with a dynamically generated selector, but instead manipulate a single instance of a jQuery object containing all the slides cached at the start. We also use the callback function provided by the fade functions to fade in the next slide after the current one has faded out.
See http://www.jsfiddle.net/b3Lf5/1/ for a simple demo
I would do it something like this:
$(document).ready(function() {
var element = '#gallery ul#gallery-container';
var idx = 0;
var timeout = 3000;
var number = $(element + ' li').length;
setInterval(function () {
idx = (idx + 1) % number;
$(element + ' li:visible').fadeOut();
$(element + ' li:eq(' + idx + ')').fadeIn();
},timeout);
$(element + ' li:not(:first)').hide();
});
Or better still, wrap it in a plugin:
(function ($) {
$.fn.customGallery = function (options) {
defaults = {
timeout : 3000
};
options = $.extend(defaults, options);
return this.each(function () {
var idx = 0, number = $(this).children('li').size(), element = this;
setInterval(function () {
idx = (idx + 1) % number;
$(element).children('li:visible').fadeOut();
$(element).children('li:eq(' + idx + ')').fadeIn();
},options.timeout);
$(element).children('li:not(:first)').hide();
});
};
}(jQuery));
jQuery(document).ready(function($) {
$('#gallery-container').customGallery()
});
edit: Edited the plugin code to bring it into line with good practice.

Categories