Assigning elements somewhat broken in javascript?
javascript, jquery
Solution
That happens because `fadeOut` has asynchronous callback, which is called when `while` loop is already passed to the last element of the array.
One possible solution is to add a closure that will keep each value of `box` for future callbacks:
while (elements.length > 0) {
(function(box) {
var errTab = $('#error');
errTab.fadeOut(10, function() {
box.css('border', '1px solid red');
errTab.html(messages.pop());
}).fadeIn(10);
errTab.fadeOut(5000, function() {
box.css('border', '1px solid #cccccc');
errTab.html(' ');
}).fadeIn(1000);
})($(elements.pop()));
}
DEMO: http://jsfiddle.net/aRV7q/5/
Problem
http://jsfiddle.net/aRV7q/1/ ``` function multierror(elements, messages){ while(elements.length > 0){ box = $(elements.pop()); errTab = $('#error'); errTab.fadeOut(10, function(){ box.css('border', '1px solid red'); errTab.html(messages.pop()); }).fadeIn(10); errTab.fadeOut(5000, function(){ box.css('border', '1px solid #cccccc'); errTab.html(' '); }).fadeIn(1000); } } ``` This is the function I'm trying to run, it should fade some messages on $('#error') and highlight some input boxes I have in a form. The messages are on the messages variable and the #name of the input boxes are on the elements variable. But what is happening is that the message gets popped and shown correctly, but the element selected to highlight is always the same, although an item is always popped when the while loop iterates, so I guess once set, the variable box is never reassigned, but I see no reason why. Any thoughts?