0
<script type="text/javascript">
function translateIt() {
        Microsoft.Translator.Widget.Translate("en", "es");
    }
</script>

<button onclick="translateIt()">Translate</button>
<script type="text/javascript">
document.getElementById("btn").onclick = function () {
        Microsoft.Translator.Widget.Translate("en", "es");
    }
</script>

<button id="btn">Translate3</button>

This html block contains two buttons that should perform the exact same function. As such, the top button works but the bottom button doesn't. What is the difference between the 'onclick' implementation within html vs. within javascript?

2 Answers2

2

If your second script example appears before the button, the getElementById will find no element.

By moving the script tag to after the element, it will work like normal.

<button id="btn">Translate3</button>

<script type="text/javascript">
document.getElementById("btn").onclick = function () {
        Microsoft.Translator.Widget.Translate("en", "es");
    }
</script>
Fenton
  • 241,084
  • 71
  • 387
  • 401
2

The difference isn't with the click handler, the difference is the order of execution. In the first example you define something (the function) then reference it (in the HTML). In the second example you reference something (the HTML element) and then define it.

So in the second example the call to getElementById("btn") doesn't find anything, because at the time it executes that element doesn't exist yet.

HTML and JavaScript execute in the order in which they exist on the page as the page is being rendered. From the top of the document to the bottom.

David
  • 208,112
  • 36
  • 198
  • 279