Forum Moderators: open

Message Too Old, No Replies

Call function only once during for loop?

         

JAB Creations

8:50 pm on Apr 22, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



How can I call a function such as the_alert() only once during a for loop?

- John

for(i=0; i < elements.length; i++)
{
if (!elements[i].onclick)
elements[i].addEventListener('click',change,false)
elements[i].addEventListener('keypress',change,false)
}

function the_alert() {alert('This alert should only execute once.');}

Little_G

9:23 pm on Apr 22, 2008 (gmt 0)

10+ Year Member



Hi,

Something like this?

for(i=0; i < elements.length; i++)
{
if (i==0){the_alert();}
if (!elements[ i].onclick)
elements[ i].addEventListener('click',change,false)
elements[ i].addEventListener('keypress',change,false)
}
function the_alert() {alert('This alert should only execute once.');} 

Andrew

JAB Creations

9:38 pm on Apr 22, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I just tried your suggestion, using i, [i], and even elements[i] without any luck, hmm...

- John

Dabrowski

10:24 pm on Apr 22, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Little G's suggestion is correct. This will definately work, although I'd have done it slightly differently:

if( !i) the_alert();

Little_G

10:31 pm on Apr 22, 2008 (gmt 0)

10+ Year Member



Hi,

It works fine for me, I don't really know what could go wrong because it's so simple!
I'm assuming it isn't showing the alert box at all, if that's the case then the only thing that I can see that would cause this is if elements has a zero length.

Andrew

httpwebwitch

12:10 pm on Apr 23, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



var flag=false;

for( ... ) {

if(!flag){
the_alert()
flag=true;
}

}