JavaScript button onclick not working
Asked Answered
P

16

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.

Price answered 1/3, 2017 at 11:16 Comment(16)
Now the alert comes when I load the page not when I click on the buttonPrice
I've mistaken the code, use it like @levi has written.Discomposure
see what error you are getting in console.as your code is working fine.Pheidippides
It's working hereTrove
Your code does not demonstrate the problem you described.Maladjusted
The code works fine.Nutshell
@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.Maladjusted
@Maladjusted - 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.Pouliot
@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.Maladjusted
@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.Maladjusted
@levi — "it wouldn't break because no var was used when declaring hello" — The problem I described is one of timing not of scope.Maladjusted
@Maladjusted — 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.Pouliot
@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.Maladjusted
@levi — "if you have a better answer please share" — The question cannot be answered. The code in the question works.Maladjusted
@Maladjusted — "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.Pouliot
Facing the same issue here. Still don't know the root cause.Herndon
Y
20

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.

Yuen answered 1/3, 2017 at 11:17 Comment(0)
J
35

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>
Jelly answered 7/8, 2017 at 2:45 Comment(1)
I was wondering why my method named clear wasn't being called...Buffer
Y
20

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.

Yuen answered 1/3, 2017 at 11:17 Comment(0)
F
11

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.

Flow answered 20/8, 2019 at 19:55 Comment(2)
this saved my dayMerc
makes no difference for me...Dercy
L
4

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>
Lemuel answered 30/9, 2022 at 8:13 Comment(1)
I did the same mistake.Woodall
G
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!

Gibert answered 3/8, 2018 at 3:49 Comment(0)
S
2

Add:

type="button"

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

Succinate answered 30/1, 2022 at 0:43 Comment(0)
A
2

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.

Aneurysm answered 18/1, 2023 at 3:18 Comment(0)
R
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>
Rigsdaler answered 20/9, 2022 at 14:37 Comment(0)
C
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.
Creath answered 11/10, 2022 at 20:28 Comment(0)
D
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')
})();
Doited answered 1/3, 2017 at 11:17 Comment(2)
It doesn't change anything.Discomposure
Not being able to reproduce the problem doesn't answer the question.Maladjusted
R
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

Recriminate answered 14/8, 2022 at 21:52 Comment(0)
K
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

Kulun answered 29/9, 2022 at 12:35 Comment(0)
H
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.

Halidom answered 1/4, 2023 at 23:42 Comment(0)
S
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.

Submission answered 28/7, 2023 at 18:40 Comment(0)
S
0

I had a similar issue because of type="module" in my HTML script tag. Exporting the needed function using the export keyword makes the function available to be imported in the HTML.

Stoneblind answered 22/3 at 21:30 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Adjure
A
-2

Write a semicolon after hello function like this

<button onclick="hello();">Hello</button>
Antiicer answered 31/12, 2021 at 14:10 Comment(1)
This makes no difference...Seventeenth

© 2022 - 2024 — McMap. All rights reserved.