-1

WELL, I have globally declared an array and in second line the document.addEventListener("click",function1); inside the function1 I have inserted an array value and then I want to use the globally declared array data outside the addEventListener() function1 using if statement but the problem is that if statement dose not working at a time. I want to show a alert message by the if statement as if I can use the counterAll array in another place

var counterAll = new Array();
var f1 = document.getElementById("f1");
f2.addEventListener("click",function1);
function function1(){
    counterAll[0] = 13;
}
if(counterAll[0]===13){
alert("It work's");
}

1 Answers1

-1

Seems like you need real understanding of javascript here, first of all your code f2.addEventListener("click",function1);

just register a function to be executed, but doesn't do anything.

function function1(){
        if(counterAll[0] == 13){
           alert('works');
        }
    }

Above code is function declaration,(its not executed till this point)

if(counterAll[0]===13){
alert("It work's");
}

Above code executes straight away, but counterAll[0] is undefined, because the function which is setting the value has not been called yet, so try below code and understand it

var counterAll = new Array();
var f1 = document.getElementById("f1");
f2.addEventListener("click",function1);
function setValue(){
    counterAll[0] = 13;
}

function function1(){
    if(counterAll[0] == 13){
       alert('works');
    }
}

setValue();

I have created a separet function setValue() in which I am setting the value. Now when i will click the Dom element with the id 'f1', the alert will show up

nobalG
  • 4,544
  • 3
  • 34
  • 72