-1

This is not a duplicate of "Why does jQuery or a DOM method such as getElementById not find the element?". I have a form that is supposed to trigger a bunch of events but none of the functions get called. I added a button just for the purpose of testing.

The HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset ="utf-8" />
    <title>Sign in</title>
    <link rel="stylesheet" type="text/css" href="main.css" />
    <link rel="stylesheet" type="text/css" href="passphrase.css" />
</head>
<body>
    <noscript>
        Javascript is disabled. Now redirecting.
    <meta HTTP-EQUIV="REFRESH" content="0; url=passnojs.html"> 
    </noscript>
    Welcome.
    <form method="post" action="prolevel2.php" id="loginForm">
        <!--code snipped-->
        <br /><br /><input type="button" value="big ugly button" id="testing" />
    </form>
    <script src="verify.js"></script><!--this should work because it's after the HTML-->
</body>
</html>

Included external JavaScript

alert("begining")
document.getElementById('testing').addEventListener('onclick', display, false)
alert("here now")
function display()
{
    alert("now displaying")//doesn't work
}

"begining" and "here now" are displayed but "now displaying is not". There are no messages in the console. What am I doing wrong?

Community
  • 1
  • 1
Celeritas
  • 12,953
  • 32
  • 95
  • 174

2 Answers2

2

Try this

document.getElementById('testing').addEventListener('click', function(){alert("now displaying")}, false);

or

document.getElementById('testing').addEventListener('click',display, false);
HIRA THAKUR
  • 15,044
  • 14
  • 47
  • 82
  • There is no need to add anonymous function... `....('click', display...` will work. – Givi Jul 26 '13 at 20:39
  • Yes he only forgot to actually call the function he declared – hayonj Jul 26 '13 at 20:40
  • How do you know when to drop the `on` prefix? Is it only used in inline event handlers? – Celeritas Jul 26 '13 at 21:00
  • this is the syntax for addEventListener. if you give click event inline ,then you have to write onclick. https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener – HIRA THAKUR Jul 26 '13 at 21:02
0

You have a syntax error, as others have mentioned. "onclick" should be "click". For default events, i prefer using the attribute instead of addEventListener, which throws a proper syntax error if entered incorrectly:

alert("begining")
document.getElementById('testing').onclick = display;
alert("here now")
function display()
{
    alert("now displaying");//doesn't work
}

http://jsfiddle.net/MaxPRafferty/N4qGB/

MaxPRafferty
  • 4,276
  • 4
  • 25
  • 37