In your html code, you’re referring to a function (convertString()
) which is defined outside the html page, in a separate file. You need to reference the JS file from your HTML page
<script src="path/to/script.js"/>
It is usually better to include JS files at the bottom of the page, in order for the browser to download every other file and start its JS engine at last
function convertString() {
let code = document.getElementById("codeInput").value
document.getElementById("code").innerHTML = code
}
.code {
color: #162;
}
.default {
display: block;
margin: 8px;
}
<body>
<div class="default">
<input type="text" id="codeInput" placeholder="document.write(`Hello, world!`)" value="document.write(`Hello, world!`)" class="code">
<br/>
<button onclick="convertString()">Run</button>
</div>
<div class="default">
<div id="code"></div>
</div>
it is not good to called script tag and render something there sometimes it won’t work if it is not the JavaScript code
I am trying to make a one line JavaScript code software and right now it looks perfectly fine… until you hit the run button. Instead of running the code (like it’s supposed to), it does absolutely nothing. So yeah, you can see the problem I am having with this.
Here’s my HTML (in case you want to look over it):
<!DOCTYPE html>
<html>
<body>
<div class="default">
<input type="text" id="codeInput" placeholder="document.write(`Hello, world!`)" value="document.write(`Hello, world!`)" class="code">
<br/>
<button onclick="convertString()">Run</button>
</div>
<div class="default">
<script type="text/javascript" id="code">
document.write(`Hello, world!`)
</script>
</div>
</body>
</html>
Here’s my JavaScript:
function convertString () {
let code = document.getElementById("codeInput").value
document.getElementById("code").innerHTML = code
}
And here’s my CSS (not sure why I put this in here, but you can look over it if you want to):
.code {
color: #162;
}
.default {
display: block;
margin: 8px;
}
So uhh… I’m having trouble. can you please help me?
<h1>Thank you!</h1>
Edit 1 (4 Jul 2020): No, this is not the same as stackoverflow.com/questions/1197575. S/he was trying to use onload=""
to do a <script></script>
inside the onload=""
. I am trying to call a function with a separate run function in my JavaScript and using a separate <script></script>
tag.
Where are you including your JavaScript code from your HTML? Do you see any errors in the console?
The problem that you are having is you are trying to run javascript by simply using javascript to place it into script tags like it is a string. There is a very frowned upon and potentially dangerous solution for what you are trying to do and that is use
It takes more effort to answer the question so it’s good idea to mark it as accepted if you do