phil_sw
phil_sw

Reputation: 61

Calling an alert function from a button but without using onclick

What im trying to do, is to call my function from whenever someone clicks on my button. However, i know that it can be done with

<button onclick="myFuntion()>

But i want to skip that step, i dont want a function in my button, i've heard that its bad programming.

However, heres how my file looks.

<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<script type="text/javacript" src="javascript.js"> </script>
<title> Javascript </title>

<script>

function testFunction(){
document.getElementById("test").onclick = Hello;
}
function Hello(){
    alert("Hello");
}
</script>
</head>

<body>
<button type="button" id="test" <!-- I know i can use onclick="testFunction()" here but i dont wanna !-->> Click me </button>

</body>

</html>

So how come it doesnt pop-up with the box "Hello" whenever i push the button, what have I done wrong?

Upvotes: 0

Views: 5565

Answers (3)

jsbueno
jsbueno

Reputation: 110301

You have to call your testFunction after the HTML body is loaded so that it actually creates he binding.

That is, at the end of the file, you'd do something like:

...
<script>
   testFunction()
</script>
</body>
...

If you run that binding code in your head script the button element won't exist yet — that is why this have to be at the end.

JavaScript libraries such as jQuery make this more elegant by providing an ready hook, where one puts code to be called once the page is fully loaded, without having to resort to code on the bottom of the page.

Complete example with script at end (confusingly, Stack Snippets don't show it to you in the order they actually are in the snippet; even though it doesn't look like it, the script is at the end here):

// Scoping function to avoid creating unnecessary globals
(function() {
  // The click handler
  function Hello() {
    alert("Hello");
  }

  // Hooking it up -- you *can* do it like you did:
  //document.getElementById("test").onclick = Hello;
  // ...but the modern way is to use addEventListener,
  // which allows for more than one handler:
  document.getElementById("test").addEventListener(
    "click", Hello, false
  );
})();
<button type="button" id="test">Click me</button>

Upvotes: 5

jsquerylover
jsquerylover

Reputation: 56

window.onload=testFunction;
function testFunction(){
document.getElementById("test").onclick = Hello;
}
function Hello(){
    alert("Hello");
}

Upvotes: 0

Maettel
Maettel

Reputation: 46

Just run the line in your testFunction always. As seen here: https://jsfiddle.net/arugco4b/

Upvotes: -1

Related Questions