1

I have this javascript code

function change (elem){
  if (x==1) elem.innerHTML = "1";
  else elem.innerHTML = "not 1";
}
var test = document.getElementById ("abc");
var x=1;

test.addEventListener ("click", change(test));

and the html looks like this

<body>
  <div id="abc">a div</div>
</body>

How do I prevent the function from being executed until the div element is clicked? Right now it just changes the innerHTML by itself and I want it to wait for the click listener.

Acestete
  • 23
  • 3

4 Answers4

6

It's being executed immediately because you're calling it immediately:

test.addEventListener ("click", change(test));

You need to pass a function, not the result of a function call:

test.addEventListener("click",
  function() {
    change(test);
  }
);
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
0

You should call your function the following way, for example:

test.addEventListener ("click", function(){change(test)});

Here is an example fiddle

RobertoNovelo
  • 3,347
  • 3
  • 21
  • 32
0
test.addEventListener("click", function(){ change(this);});
ps.
  • 4,230
  • 5
  • 31
  • 39
0

You are immediately executing the function change() because of the parenthesis.

Another way to do what you are trying is to pass the function by reference and using this to get the element.

function change (){
  if (x==1) this.innerHTML = "1";
  else this.innerHTML = "not 1";
}
var test = document.getElementById ("abc");
var x=1;

test.addEventListener ("click", change);
Bryant Miano
  • 689
  • 3
  • 9