-1

My Code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ATM Interfacetest</title>
<link rel="stylesheet" type="text/css" href="css/rahmen/rahmen.css">
<script>
    function testwindow(){
        var tmp = document.createElement('div');
        tmp.id = 'idtest';
        tmp.className = 'classtest';
        document.getElementById('xbuttonsHeinz-Ulf').appendChild(tmp);
        document.getElementById('idtest').addEventListener('click', test(), false);

    }

    function test(){
        alert('Alarm!');
    }
</script>

</head>
<body onload="testwindow()">
<div id="xbuttonsHeinz-Ulf" class="xbuttons">
    <div id="schließenHeinz-Ulf" class="symbol">x</div>
    <div id="minimierenHeinz-Ulf" class="symbol">&nbsp;-&nbsp;</div>
    <div id="maximierenHeinz-Ulf" class="symbol">□</div>
</div>
</body>
</html>

Drives me crazy. Trying to add the Eventlistener makes the test() function to be excuted directly, without waiting to clicked.

Whats my mistake.

I searching for a good idea to dynamically create html tags with option to add eventhandlers.

Trying:

tmp.onclick = test();

also executes the function directly w/o waiting for a click.

  • `.addEventListener("click", test(), false)` -> `.addEventListener("click", test, false)` – Andreas Jan 07 '18 at 10:40
  • You put the parentheses after the `test`, so execute it, of course. – user202729 Jan 07 '18 at 10:41
  • [Why does click event handler fire immediately upon page load?](https://stackoverflow.com/questions/7102413/why-does-click-event-handler-fire-immediately-upon-page-load) – Andreas Jan 07 '18 at 10:49

1 Answers1

2

Given the expressions

  • test() - the result of a call to the function test with no arguments passed.

  • test - a reference to the function test.

You want the latter. The former calls test as soon as the line is reached. addEventListener(...) wants a reference to an EventListener, not the result of the handled event.

Austin Brunkhorst
  • 20,704
  • 6
  • 47
  • 61