I'm pretty new to Javascript and playing around with it at the moment. However, I can't actually test my code because I get the following error:
Uncaught TypeError: namecaller is not a function
at HTMLButtonElement.onclick (Tools.html:101)
Here is my code:
div id="content">
<script>
function namecaller(){
var a = "scurvy";
var b = "dog";
document.getElementById("namecaller").innerHTML = "You are a " + a + " " + b;
}
</script>
Namecaller</p>
<button type="button" onclick="namecaller()">
You are a...</button>
I have no clue why it doesn't work, looked at other StackOverflow questions and also at the W3 tutorials.
function namecaller() {
var a = "scurvy";
var b = "dog";
document.getElementById("content").innerHTML = "You are a " + a + " " + b;
}
<div id="content"></div>
<button type="button" onclick="namecaller()">
You are a...</button>
The code seems to have a lot of problems like your tags were not in properly written. The tags need to open closed properly. And your script should be in right place so that it gets compiled. Then you have not given an id to any of the elements and try calling them. So here is the working example of how the code should be properly written for bug-free compilation.
Sometimes, it is because your function name override some other functions, especially the system defined ones. For example, I once made a function named as "translate." Later, it reports the exactly same error like yours. The solution is quite simple: just change the function name. For me, I make it "function tranlateIt()" and hence the problem is gone forever.
You have not defined the id of paragraph for which you are changing the value. Just define the Id of paragraph as namecaller and it will work. See the code below:
<div id="content">
<script>
function namecaller(){
var a = "scurvy";
var b = "dog";
document.getElementById("namecaller").innerHTML = "You are a " + a + " " + b;
}
</script>
<p id = "namecaller">Namecaller</p>
<button type="button" onclick="namecaller()">
You are a...</button
This is not the solution to your particular problem (the accepted answer answers it neatly), but the following might be the useful reference to the future readers (it happened very often to me).
The same error you provided happened to me, when I first declared a variable and then the function with the same name. For example:
var example = 5;
function example() {
console.log("The function just got executed!");
}
<button onclick="example()">Click me!</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With