I have a loop of 50 divs, in which I am assigning event based on the current element. However I want to assign event based on a condition.
For example, divs are arranged one behind another, just like a photo stack.
I want user to first hit first div, then only they should able to hit second div then third div and so on till they reach the end of divs.
Because of the below code user can hit on any of the div and perform action. But action needs to be performed one by one. One div after another. Please suggest the solution.
var flag=0;
var flipImage=document.querySelectorAll('.shadow');
for(j=0; j<flipImage.length; j++){
var currentFlipImage=flipImage[j];
if(j==flag){
flag++;
currentFlipImage.addEventListener('click',flipDown,false);
}
}
Maybe something like:
This only generates and adds event listeners when needed.
Important side note: The return value of
querySelectorAll()is aNodeListwhich is live. That means any time you calllengthon this object, the list is reevaluated (the elements are searched again) which adds a performance overhead. Thus, never uselist.lengthin theforloop. Capture thelengthbeforehand.Working DEMO
If you want to make it going in a loop, just remove the
ifstatement (keep the body of course) and do