Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't my inline JavaScript function work?

What seems to be the problem? The code doesn't work, the text does not change.

function translate() {
    document.getElementById("tex").innerHTML = "BLABLA";
}
<h1 align="center"><font size="100">What Is BLA: </font></h1>
<p id ="tex"><font size="10">BLA</font></p>
<button onclick="translate()">Translate</button>
like image 596
EGK Avatar asked Dec 13 '16 21:12

EGK


1 Answers

The problem is in some browsers, like Chrome, DOM elements have a translate property (MDN does not list Chrome as supporting this feature, but it does have the property). In the context of JavaScript event attributes, those properties shadow any globals of the same name.

If you check your developer console, you should see a message saying that translate is not a function because of this.

Uncaught TypeError: translate is not a function

If you change the name of the function, you will avoid this issue:

function myTranslate() {
    document.getElementById("tex").innerHTML = "BLABLA";
}
<h1 align="center"><font size="100">What Is BLA: </font></h1>
<p id ="tex"><font size="10">BLA</font></p>
<button onclick="myTranslate()">Translate</button>
like image 99
Alexander O'Mara Avatar answered Oct 23 '22 11:10

Alexander O'Mara