Lars Kloosterman Lars Kloosterman - 4 months ago 13
HTML Question

The onmousedown Event Doesn't Seem to be Triggering

In one of my projects the

onmousedown
event didn't seem to be doing anything when it was meant to trigger a function in a separate JavaScript file.

I tried incorporating both
onmousedown
and
onClick
on a button in a small test file to see if it was just a problem in the project, and it didn't work either, leading me to believe that I must be doing something wrong...

Here is my
test.html
file:

<!DOCTYPE html>
<html>
<body>
<button onmousedown="click()">Click</button>
<span id="testSpan"></span>

<script type="text/javascript" src="main.js"></script>
</body>
</html>


And here is my
main.js
file:

function click() {
document.getElementById("testSpan").innerHTML = "SUCCESS";
}


To explain, the HTML button is supposed to trigger the
click()
function in
main.js
, and then cause "SUCCESS" to appear through the
span
element beside the button in the webpage; which it doesn't for me.

I have tried to do the same in a pen on codepen.io where it didn't seem to work either. Even weirder is the fact that I don't have any errors showing up at all... what am I missing?

Answer

It isn't working because you named your function 'click'. I changed the name to 'press' and your code works fine!

function press() {
  document.getElementById("testSpan").innerHTML = "SUCCESS";
}
<!DOCTYPE html>
<html>
  <body>
    <button onmousedown="press()">Click</button>
    <span id="testSpan"></span>

    <script type="text/javascript" src="main.js"></script>
  </body>
</html>