performing elem.click(); in a javascript loop doesn't always work - timing?
<p>Hello I've been working on a Javascript 8 slider puzzle (that is working including event listeners) and have code that generates an array of moves (which squares/div id's the user would click) to solve the puzzle. </p>

<p>My goal is for a user to be able to click on a solve button, triggering a function that will play back that array of solution moves in the puzzle. </p>

<p>Where I'm truly stumped is for some reason, in the following code, the click doesn't work on every iteration of the loop - which screws everything up. I'd appreciate if anybody can offer any help or suggestions.</p>

<pre><code>while(k &lt; moves.length)
{ 
   var move = "vp" + moves[k];
   var el = document.getElementById(move);
   el.click();  // simulate a users click on div
   populate(); // update array
   k++;
}
</code></pre>

<p>edit - for those who asked below are event functions &amp; a little more code...</p>

<pre><code>function addEvent(elem, event, fn) {
// avoid memory overhead of new anonymous functions for every event handler that's installed
// by using local functions
function listenHandler(e) {
    var ret = fn.apply(this, arguments);
    if (ret === false) {
        e.stopPropagation();
        e.preventDefault();
    }
    return(ret);
}

function attachHandler() {
    // set the this pointer same as addEventListener when fn is called
    // and make sure the event is passed to the fn also so that works the same too
    var ret = fn.call(elem, window.event);   
    if (ret === false) {
        window.event.returnValue = false;
        window.event.cancelBubble = true;
    }
    return(ret);
}

if (elem.addEventListener) {
    elem.addEventListener(event, listenHandler, false);
} else {
    elem.attachEvent("on" + event, attachHandler);
}
}

window.onload = function() {
var height = (newImg.height*0.33);
var width = (newImg.width*0.33333);

addEvent(document.getElementById('shuffle'),'click',initGame);
addEvent(document.getElementById('vp1'),'click',move);
addEvent(document.getElementById('vp2'),'click',move);
addEvent(document.getElementById('vp3'),'click',move); // ...
</code></pre>

<p>This is first part of function that el.click(); calls...</p>

<pre><code>    function move() {

var e = this;
var id = e.id.charAt(2);

var temp = 0;
//var images = e.getElementsByTagName('img'); 
//alert(images[0].className);
if (id == 1) {
  if (document.getElementById("vp2").innerHTML.indexOf("selected") != -1)
    {    temp = e.innerHTML;
        e.innerHTML = document.getElementById("vp2").innerHTML;    
        document.getElementById("vp2").innerHTML = temp;
        numMoves++;
}else if (document.getElementById("vp4").innerHTML.indexOf("selected") != -1)
    {   temp = e.innerHTML;
        e.innerHTML = document.getElementById("vp4").innerHTML;    
        document.getElementById("vp4").innerHTML = temp;
        numMoves++;
    }
}
</code></pre>
