2

this is probably stupidly easy but I'm very new to JavaScript and it's driving me nuts.

My question, why doesn't this work: http://jsfiddle.net/Ye9tG/

<input type="button" id="butt" value="Button" onclick="getThought();"/>

It works fine if I add the onclick directly into the JavaScript:

document.getElementById("butt").onclick = getThought;

Thanks in advance.

user2999861
  • 65
  • 1
  • 5
  • Here it works now: http://jsfiddle.net/sJ9pF/ I just added the function into the dead. – jko Nov 16 '13 at 17:50
  • See this answer: http://stackoverflow.com/a/5468370/2926151, and this answer: http://stackoverflow.com/a/5830423/2926151 – Villarrealized Nov 16 '13 at 17:51

2 Answers2

3

Your getThoughts function isn't defined, because your JavaScript is set to execute onLoad. See the dropdown menu in the upper left of jsFiddle. Select "No wrap - in <head>" to resolve the issue: http://jsfiddle.net/Ye9tG/1/

Also, always take a look at your browser's console to check for errors. In this case, you'll see a Uncaught ReferenceError: getThought is not defined error when clicking the button.

Colin Brock
  • 21,267
  • 9
  • 46
  • 61
2

In the top left corner of jsfiddle you'll see that your fiddle is set to run your js code "onLoad". What that really means is that jsfiddle creates this for you:

<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){

// YOUR CODE HERE

}//]]>  

</script>

As a result, your function is only accessible within that onload function. Change the value to "no wrap head" and you'll see that it works.

Your other option would be to make your function explicitly global:

window.getThought = function(){
  // ...

http://jsfiddle.net/Ye9tG/5/

James Montagne
  • 77,516
  • 14
  • 110
  • 130