Richard
Richard

Reputation: 1041

javascript function called with an onclick attribute on button

I don't understand why this is not working. I'm sticking to the reference on w3schools. Here the code :

HTML:

<button onclick="click()">Test</button>

Javascript:

function click() {
    alert("Hello !");
}

Upvotes: 0

Views: 136

Answers (5)

sayan
sayan

Reputation: 501

you need to change the function name. 'click' might be a reserved keyword, so it wont recognize when you call it. rename it to other names eg. 'democlick()'. also don't forget to save your code with '.html. extension. please tell me if any issue exists. thanks.

Upvotes: 1

Nikhil Talreja
Nikhil Talreja

Reputation: 2774

click seems to be reserved. Try renaming the method: http://jsfiddle.net/qeCE5/1/

function clickMe() {
    alert("Hello !");
}

Upvotes: 1

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382132

This code doesn't work because there's already a click native method and shadowing it prevents the normal click event handling. Give it another name and it will work.

A way to see that is to define your button as

<button onclick="console.log(click)">Test</button>

Upvotes: 2

Mritunjay
Mritunjay

Reputation: 25882

I think you cann't give a function name as click. Change your function name & it should work.

Upvotes: 1

Quentin
Quentin

Reputation: 943510

It doesn't work because you have configured JSFiddle to wrap the JavaScript in a function and call it onload. This stops your function being a global so it isn't in scope for your intrinsic event handler attribute.

Additionally, after you fix that, the weird scoping rules for intrinsic event attributes (I have no idea where these are documented) means that click is resolved as the button's click property before the scope is searched far enough to find the global click function.

The quick and dirty solution is:

  • Rename the function to something that doesn't clash with existing property names
  • Pick a no wrap option from the menu on the left of JSFiddle

The proper solution is to attach your event handlers with JavaScript. This isn't the 1990s and we should avoid using the techniques of that era that fail to separate concerns. Keep your JS in one place and your HTML in another.

<button>Test</button> 

<script>
document.querySelector('button').addEventListener('click', click);
function click(evt) {
    alert("Hello !");
}
</script>

Upvotes: 4

Related Questions