1

Why won't this give an alert? I need to make it work without JQuery and with the "button" element since the button is being auto-generated. It works if I put the javascript inside the quotes, but I want to call a function.

<button onclick='test()' >click</button>

javascript

function test()
{
alert('hi');
}

https://jsfiddle.net/nn90okdj/1/

3
  • 4
    You code works as it is. In your fiddle you've wrapped the code within onload handler, which excludes test from the global scope. Commented Aug 9, 2017 at 17:11
  • Your code is fine jsFiddle is acting weird. I had to wrap JS in script tags to get to work in jsFiddle jsfiddle.net/nn90okdj/16 Commented Aug 9, 2017 at 17:25
  • Maybe a bit aside, but as a big fan of delegated events, I can insure you, that you can delegate events without jQuery as easily as with jQuery, you really don't need an inline handler. Commented Aug 9, 2017 at 17:46

4 Answers 4

1

Fiddle is being weird. Your code is fine.

https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_ev_onclick

Sign up to request clarification or add additional context in comments.

Comments

0

Seems to work right for me here.

function test()
{
alert('hi');
}
<button onclick='test()' >click</button>

1 Comment

That works inside of stackoverflow, but not in jsfiddle. weird.
0

Your function is not working correctly because, script is getting loaded at top of the html page. It should be loaded at the bottom if you want to access the DOM element

  • Click on the Javascript button
  • Select No wrap in body
  • It should work properly now

To rectify this.

Javascript Configuration

Comments

0

The function test does not work in the jsFiddle environment because what you write in the javascript section is placed into the window.onload handler by jsFiddle.

If you do not want to change any settings, directly add to the global scope like here: https://jsfiddle.net/93a8rtaf/

this.test = function () {
  alert('hi');
}
<button onclick='test()' >click</button>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.