get each element from array at a time with jquery - javascript

I need to get all elements from array but one at a time and only to show up after something had been done with previous element. For example:
var elems = ['Apple','Orange','Banana'],
i = 0;
elems.forEach(function(e){
elems[i++].fadeIn(200, arguments.callee); // here I need some kind of callback function to process first element, and only when that's finished, another element should fadeIn.
});
Thank you.

You could use a recursive function
var elems = ['Apple','Orange','Banana'],
i = 0;
function (recursive(elem) {
$(elem).fadeIn(200, function() {
recursive(elems[++i]);
});
})(elems[0]);
or just delay()
var elems = ['Apple','Orange','Banana'],
i = 0;
$.each(elems, function(i, e){
e.delay(i*speed).fadeIn(200);
});

Use following
$(function(){
var myArray = ['Apple','Orange','Banana'];
var i=0;
$.each(myArray, function(index, value){
elems[i++].fadeIn(200, arguments.callee); // here I need some
});
});

Related

How can I put the results in an array after use each in javascript?

Hi I have this function:
changeTarea: function() {
var self = this;
$("#select_tarea_id").change(function() {
var id_tarea = $("#select_tarea_id").val();
$.each(self.objTareasFlot, function(index,value) {
for(var i = 0; i < value.length; i++) {
if(value[i].Id == id_tarea) {
self.objTareasFlotFinal['id']=value[i].Id;
self.objTareasFlotFinal['id_pro']=value[i].Id_proyecto;
self.objTareasFlotFinal['tarea']=value[i].nombre_tarea;
self.objTareasFlotFinal['porcentaje']=value[i].porcentaje;
console.info(self.objTareasFlotFinal);
}
}
});
});
}
And the function print :
But I need the 3 results in one array
for example :
How can I do that with that function? Sorry for my english I did try to explain of the better way
You can declare an array and push populated object into it. Something like this:
changeTarea: function(){
var self = this;
var container[];
$("#select_tarea_id").change(function() {
var id_tarea = $("#select_tarea_id").val();
$.each(self.objTareasFlot, function(index,value) {
for(var i = 0; i < value.length; i++){
if(value[i].Id == id_tarea){
self.objTareasFlotFinal['id']=value[i].Id;
self.objTareasFlotFinal['id_pro']=value[i].Id_proyecto;
self.objTareasFlotFinal['tarea']=value[i].nombre_tarea;
self.objTareasFlotFinal['porcentaje']=value[i].porcentaje;
console.info(self.objTareasFlotFinal);
container.push(self.objTareasFlotFinal);
}
}
});
});},
Create an array variable var result = []; inside your function.
Within your loop push() the objects into it;
results.push(self.objTareasFlotFinal);
var newArray = [];
self.objTareasFlotFinal['id']=value[i].Id;
self.objTareasFlotFinal['id_pro']=value[i].Id_proyecto;
self.objTareasFlotFinal['tarea']=value[i].nombre_tarea;
self.objTareasFlotFinal['porcentaje']=value[i].porcentaje;
newArray.push(self.objTareasFlotFinal);
// console.log should show the results
console.log(newArray);
If this array is meant to be global and accessible outside the function, you might want to define newArray outside the function first and remove the var from it within the function.
Then every time somebody runs the function, a new object is added to the array.
Alternatively, you could just return the array as the final value:
var newArray = [];
self.objTareasFlotFinal['id']=value[i].Id;
self.objTareasFlotFinal['id_pro']=value[i].Id_proyecto;
self.objTareasFlotFinal['tarea']=value[i].nombre_tarea;
self.objTareasFlotFinal['porcentaje']=value[i].porcentaje;
newArray.push(self.objTareasFlotFinal);
return newArray;

Need help in my jquery plugin

Last week a made a function for ellipsing the text inside some selector.
I was calling the function like this:
ellipsiText('.class',50) passing the selector and the max length of the text that i wanted to. This works fine, but im trying to make it a plugin, to call like this: $('.class').ellipsiText(50).
So, i was reading the tutorial in jquery website, and i understood how to do it. But i think i'm having an issue with the "this" seletor. Here is my original function:
function ellipsiText(selector,maxLength){
var array = $(selector).map(function(){
return $(this).text();
}).get();
var i;
var teste = [];
for (i=0;i<array.length;i++){
if (array[i].length > maxLength){
teste.push(array[i].substr(0,maxLength) + "...");
} else {
teste.push(array[i]);
}
}
for (var i=0;i<teste.length;i++){
$(selector).each(function(i){
$(this).text(teste[i]);
});
}
}
and here is my tentative of making a jquery plugin:
(function ($) {
$.fn.ellipsiText = function(length){
var array = $(this).map(function(){
return $(this).text();
}).get();
var i;
var teste = [];
for (i = 0; i < array.length; i++){
if (array[i] > length){
teste.push(array[i].substr(0,length) + "...");
} else {
teste.push(array[i]);
}
}
$(this).each(function(i){
$(this).text(teste[i]);
});
};
}(jQuery));
What am i doing wrong?
Well first thing is not a problem, but instead of $(this) in the first function scope, you can use this.map/this.each.
The problem is, in the second code you do
if (array[i] > length)
instead of
if (array[i].length > length)
Nothing to do with the jQuery plugin!
http://jsfiddle.net/UY88r/
This is untested, but the basic structure is something like this. Also you have so much looping in your code when one loop is needed.
$.fn.ellipsiText= function(options) {
var settings = $.extend({ //nice way to give to give defaults
length : 50,
ellipsi : "..."
}, options );
return this.each(function() { //the return is needed for chaining
var elem = $(this);
var txt = elem.text();
if (txt.length>settings.length) {
elem.text(txt.substr(0,settings.length) + settings.ellipsi );
}
});
};
and call it
$( "div.defaults" ).ellipsiText();
$( "div.foo" ).ellipsiText({
length : 10
});
$( "div.more" ).ellipsiText({
length : 10,
ellipsi : "<more>"
});
You already have a working function, just use it.
$.ellipsiText = ellipsiText;
$.fn.ellipsiText = function (count) {
ellipsiText(this, count);
}
now you can use it like any of the following:
ellipsiText('.class',50);
$.ellipsiText('.class',50);
$('.class').ellipsiText(50);
There's no sense in rewriting the function you already have working when you can just use it.

creating dynamic elements with jquery click event always returns last index in for loop

I have something like this:
var a = {
generateDynamicStuff: function(data) {
for(var i=0;i<data.length;i++) {
var dyn_div = document.createElement('div');
dyn_div.className = "dyn_div_"+data[i].name;
dyn_div.textContent = data[i].name;
document.getElementByClassName("dyn_list")[0].appendChild(dyn_div);
$(document).on("click", ".dyn_div_"+data[i].name, function() { alert(i); a.otherFunction(i);});
}
},
otherFunction: function(some_index) {....}
}
The idea is, I am given a list of names which I will generate clickable div elements with. When one of these divs are clicked, its index will be passed to otherFunction().
The problem is, function() { alert(i); a.otherFunction(i);} always gives the last index. That is, if I have 5 items, then i in the anonymous function is always giving me "4" no matter which div I am clicking.
Why is this?
here is the scope problem here click event just binds the function not execute at binding time it executes when actually event occurs at that time it takes the last value of 'i' so you can try this
var a = {
generateDynamicStuff: function(data) {
for(var i=0;i<data.length;i++) {
var dyn_div = document.createElement('div');
dyn_div.className = "dyn_div_"+data[i].name;
dyn_div.textContent = data[i].name;
dyn_div.setAttribute("index", i);
document.getElementByClassName("dyn_list")[0].appendChild(dyn_div);
$(document).on("click", ".dyn_div_"+data[i].name, function(e) {
var index = $(this).attr("index");
alert(index);
a.otherFunction(index);
});
}
},
otherFunction: function(some_index) {....}
}
It is the classic closure variable in a loop issue
var a = {
generateDynamicStuff: function (data) {
var $ct = $('.dyn_list');
$.each(data, function (i, data) {
$('<div />', {
'class': "dyn_div_" + data.name,
text: data.name
}).appendTo($ct).on('click', function () {
alert(i);
a.otherFunction(i);
})
})
},
otherFunction: function (some_index) {....
}
}

Variable in nested function returns undefined

The variable my_sound is declared in the first, outer function. So, I should be able to use it in the nested function. However the mouseout event produces no result. What am I doing wrong? Thanks for any help.
$(document).ready(function () {
var starting_pics = ["CN.gif", "EN.gif", "GN.gif"];
var starting_sounds = ["CN.mp3", "EN.mp3", "GN.mp3"];
var i = 0;
for (i = 0; i < starting_pics.length; i++) {
$("<img/>").attr("src", "images/" + starting_pics[i]).appendTo("#main").addClass("pics");
}
$("#main").on("click", ".pics", function () {
var i = $(this).index();
var my_sound =($("<audio/>").attr("src", "audio/" + starting_sounds[i])).load().get(0).play();
$("#main").on("mouseout", ".pics", function () {
$("my_sound").animate({ volume: 0 }, 1000);
});
});
});
The problem is probably that .play() doesn't return a jQuery object (or anything, for that matter, hence undefined).
Additionally, as the other comments have said, you don't want $('my_sound').whatever but rather just my_sound.whatever if it were a jQuery object, which it is not. So maybe you could try
var $my_sound = $("<audio />").attr("suchandsuch","etc");
$my_sound.load().get(0).play();
$my_sound.whatever();

Not allowing to push duplicate items into array

Basically I'm pushing containers into an array, and once one has been pushed, I don't want to allow that same one to be pushed again.
Here is my JSfiddle: http://jsfiddle.net/9Dmcg/3/
Javascript:
$(document).ready(function(){
var favorites = [];
var counter = 0;
$('.containers').on('click', function(){
favorites.push($(this).clone())
$('.favorite').append(favorites);
});
});
I need to find a way to work around that.
Unless there's more to that click event, you can use the .one() method in place of .on to get this functionality.
$(document).ready(function(){
var favorites = [];
var counter = 0;
$('.containers').one('click', function(){
favorites.push($(this).clone())
$('.favorite').append(favorites);
});
});
http://jsfiddle.net/9Dmcg/4/
Even if there were more to it, you could still use .one():
$(document).ready(function(){
var favorites = [];
var counter = 0;
$('.containers').one('click', function(){
favorites.push($(this).clone())
$('.favorite').append(favorites);
$(this).on("click",function(){
alert("Favorite Added!");
}).triggerHandler("click");
});
});
http://jsfiddle.net/9Dmcg/5/
Try to check for element id's I would say. Something like this:
$(document).ready(function(){
var favorites = [];
var counter = 0;
$('.containers').bind('click', function(){
var isAdded = false;
for (var f = 0; f < favorites.length; f++) {
console.log(favorites[f].id + "|" + this.id);
if (favorites[f].id === this.id)
isAdded = true;
}
if (!isAdded)
favorites.push($(this).clone()[0])
console.log(favorites);
$('.favorite').append(favorites);
});
});
And here's working example -> http://jsfiddle.net/9Dmcg/7/
mz
This can be done using the JS Proxy (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy)
Following is the code to create an array which will not accept duplication entry
var arr = new Proxy([], {
get: function(target, key) {
return target[key];
},
set: function(target, key, value){
if(target.indexOf(value)>=0) return false;
target[key] = value;
return true
}
});
arr.push(100);
arr.push(100); // this will throw error
In the above code, we are modifying the default behaviour of array as the set method will be called on any modification done on the array.
You can check if the element already exists:
$(document).ready(function(){
var favorites = [];
$('.containers').on('click', function(){
var found = false;
for(var i = 0; i < favorites.length; i++)
{
if (favorites[i] == $(this)) found = true;
}
if (!found) favorites.push($(this).clone())
$('.favorite').append(favorites);
});
});
Add a class to items that have been pushed, and then do a basic check:
Instead of:
favorites.push($(this).clone())
you can do:
if( !$(this).hasClass("pushed") ) {
favorites.push( $(this).addClass("pushed").clone() );
}
Just push the element itself instead of cloning it:
favorites.push($(this))
The added benefit is that it gives the user a clue that the item has already be added.
Live demo: http://jsfiddle.net/9Dmcg/6/
Seems like your looking for Array.indexOf. It returns the index of the value on an array. Returns -1 if not found.
It is a new array method, so you will need a polyfill for it to work on old browsers.
$(document).ready(function(){
var favorites = [];
var counter = 0;
$('.containers').on('click', function(){
var clone = $(this).clone(); // caching element
if (favorites.indexOf(clone) !== -1) {
favorites.push(clone);
}
$('.favorite').append(favorites);
});
});

Categories