19

<button onclick="hello()">Hello</button>

<script>
  function hello() {
    alert('Hello');
  }
</script>

This is my code. But it's not working. When I click on the button nothing happens.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Martin W
  • 4,548
  • 3
  • 16
  • 27
  • Now the alert comes when I load the page not when I click on the button – Martin W Mar 01 '17 at 11:19
  • I've mistaken the code, use it like @levi has written. – kind user Mar 01 '17 at 11:20
  • see what error you are getting in console.as your code is working fine. – santosh gore Mar 01 '17 at 11:23
  • It's working here – Vilas Kumkar Mar 01 '17 at 11:23
  • 3
    Your code does not demonstrate the problem you described. – Quentin Mar 01 '17 at 11:23
  • The code works fine. – Roy Bogado Mar 01 '17 at 11:23
  • @levi — Why would delaying the creation of the function help? If anything, that would break it because there could be a period between the button rendering and the rest of the page fully loading (especially if it includes large images) where the load event hasn't fired. – Quentin Mar 01 '17 at 11:25
  • @Quentin - in some cases the DOM has not yet finished loading. sounds like a reasonable case to test for when an event is not firing from an inline onclick attribute. besides, it wouldn't break because no `var` was used when declaring `hello` - placing it right on the window. –  Mar 01 '17 at 11:56
  • @levi — "in some cases the DOM has not yet finished loading" — Which isn't a problem until you delay the creation of the function until after it has. – Quentin Mar 01 '17 at 11:59
  • @levi — "sounds like a reasonable case to test for when an event is not firing from an inline onclick attribute" — Not when there is no DOM access going on in the existing JavaScript. – Quentin Mar 01 '17 at 12:00
  • @levi — "it wouldn't break because no var was used when declaring hello" — The problem I described is one of **timing** not of scope. – Quentin Mar 01 '17 at 12:00
  • @Quentin — even if its not the case, loading scripts in an onload or on DOMContentLoaded is a better practice. besides, I saw the comment from Kind user and saw that it was missing a function inside. it might not be the answer, but its not farfetch. if you have a better answer please share. –  Mar 01 '17 at 12:31
  • @levi — "loading scripts in an onload or on DOMContentLoaded is a better practice" — No, it isn't. Attaching event listeners then often is, loading scripts is not. – Quentin Mar 01 '17 at 12:48
  • @levi — "if you have a better answer please share" — The question cannot be answered. The code in the question works. – Quentin Mar 01 '17 at 12:48
  • @Quentin — "Attaching event listeners then often is, loading scripts is not" javascript is consisted not only of event listeners, but variable declarations, UI logic etc... you should look into it. –  Mar 01 '17 at 13:21
  • Facing the same issue here. Still don't know the root cause. – Johan Aug 02 '23 at 06:25

15 Answers15

33

Note to other developers coming across this, you can run into this if you use a reserved method names e.g. clear.

<!DOCTYPE html>
<html>
<body>
  <button onclick="clear()">Clear</button>
  <button onclick="clear2()">Clear2</button>
  <script>
  function clear() {
    alert('clear');
  }
  function clear2() {
    alert('clear2');
  }
  </script>
</body>
</html>
Michael
  • 11,571
  • 4
  • 63
  • 61
18

How about this?

<button id="hellobutton">Hello</button>
<script>
function hello() {
alert('Hello');
}
document.getElementById("hellobutton").addEventListener("click", hello);
</script>

P.S. You should place hello() above of the button.

Kangjun Heo
  • 1,023
  • 1
  • 8
  • 19
10

Ran into this problem myself so I can confirm something's not right. The difference is that I am generating the DOm Element at runtime. Replacing onclick with onmousedown seemed to do the trick if you can't find a place to addEventListener in your code.

Edward
  • 495
  • 1
  • 6
  • 20
2

I had a similar issue. I had child.js and a common.js files. In my case, My HTML file was using both the JS files and both of them had a function with the same name,

child.js

function hello(){}

and also

common.js

function hello(){}

After I remove one of these my code works fine and onclick started working. hope this helps!

tk_
  • 16,415
  • 8
  • 80
  • 90
1

Add:

type="button"

to the button element. The default type is "submit" which is submitting the form before the script is run.

Sean
  • 2,033
  • 2
  • 23
  • 28
1

I had the same issue, for me, it did not work because of my main.js having type="module", if you don't need type="module" this will work.

<body>
    <button onclick="onBtSave()">Save filter model script type module</button>
    <button onclick="onBtRestore()">Restore filter model no script type</button>
    
    <script type="module">
      // broken 
      function onBtSave() {
        console.log("saving current filter model");
      }
    </script>
    <script >
      // working 
      function onBtRestore() {
        console.log("restoring current filter model");
      }
    </script>
1

I had the same problem and that's because of reserved method names. We just change the function name.

function click() {
    alert('hi')
    
}

function click1234() {
    alert('hi')
    
}
<body>
<button onclick="click()">login</button>

<button onclick="click1234()">login1234</button>
</body>
Nick Vu
  • 14,512
  • 4
  • 21
  • 31
mojtaba
  • 11
  • 1
1

using onclick vs EventListeners.

The question is a matter of browser compatibility and necessity. Do you need to attach more than one event to an element? Will you in the future? Odds are, you will. attachEvent and addEventListener are necessary. If not, an inline event may seem like they'd do the trick, but you're much better served preparing for a future that, though it may seem unlikely, is predictable at least. There is a chance you'll have to move to JS-based event listeners, so you may as well just start there. Don't use inline events.

jQuery and other javascript frameworks encapsulate the different browser implementations of DOM level 2 events in generic models so you can write cross-browser compliant code without having to worry about IE's history as a rebel. Same code with jQuery, all cross-browser and ready to rock:

$(element).on('click', function () { /* do stuff */ });

Don't run out and get a framework just for this one thing, though. You can easily roll your own little utility to take care of the older browsers:

function addEvent(element, evnt, funct){
  if (element.attachEvent)
   return element.attachEvent('on'+evnt, funct);
  else
   return element.addEventListener(evnt, funct, false);
}

// example ~``` addEvent( document.getElementById('myElement'), 'click', function () { alert('hi!'); } );

Try it: http://jsfiddle.net/bmArj/

Taking all of that into consideration, unless the script you're looking at took the browser differences into account some other way (in code not shown in your question), the part using addEventListener would not work in IE versions less than 9.
1

For other devs with more advanced code, sometimes an absolute position element is blocking the button. Make sure no element is blocking the button(s) from being clicked.

LordDeath
  • 11
  • 2
0

There is no problem with your code.. run this snippet

function hello() {
alert('Hello');
}
<button onclick="hello();">Hello</button>

and if you want to alert this on window load. change your code like this way

(function(){
  alert('hello')
})();
Jishnu V S
  • 8,164
  • 7
  • 27
  • 57
0

In my case there are was two same elements with position: absolute. I set onclick on the first one so it haven't been called because second element was covering it

LaJ HerE
  • 3
  • 2
0

This happened to me when I opened another folder in visual studio code. I just opened new window of visual studio code and only opened one folder this time and it now works

username
  • 1
  • 1
0

I ran into the same problem when I had a button with an id that exactly matches the JavaScript function name. After changing one of them so that the id and function name don't match, it worked.

0

For anyone who may be half as dumb as I am, make sure you didn't make a backup of your code and keep the backup open in your browser while adding your button in the new code.

person the human
  • 345
  • 4
  • 15
-2

Write a semicolon after hello function like this

<button onclick="hello();">Hello</button>
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103