-3

I have this code:

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>
<script>
var txt = '{"name":"John", "city":"New York"}'
var obj = JSON.parse(txt);
document.getElementById("demo").innerHTML = obj.name;
</script>

</body>
</html>

How to put the script in another file named "myscript.js" and connect to html page? I want to do that because i want to link the script to multiple html pages and sometimes i need to change var txt = '{"name":"John", "city":"New York"}'

Thank you!

Duty Alex
  • 35
  • 6

2 Answers2

0

Just put everything between the script tags in a text file and save it as myscript.js

then replace your script tags in the html with

<script src="myscript.js"></script>
DaveP
  • 109
  • 1
  • 9
-3

You can do like that;

<head>
    <script type="text/javascript" src="your/file/address/fileName.js"></script>
</head>
Esat ARSLAN
  • 119
  • 7
  • better to place before closing `

    ` tag ^^

    – treyBake Oct 30 '18 at 09:14
  • also, there's use of single quotes and double quotes within the same line - stick to one for practices sake :) – treyBake Oct 30 '18 at 09:17
  • 1
    The script in the question depends on appearing *after* the paragraph in the DOM, so moving it to the head as you demonstrate here will break it. – Quentin Oct 30 '18 at 09:19