buggenerator buggenerator -4 years ago 193
Javascript Question

include an external JS file into HTML

I am trying to learn javascript (from coursera). Before you downvote me to hell, please note that i am newbie in javascript. We have an assignment where i need to insert an external javascript file in a html.


<!DOCTYPE html>
<title>Color Guessing Game</title>
<body onload="do_game()">
<script type="text/javascript" src="/colguess.js"></script>

JS File

var guess_input_color;
var finished=false;
var colors=["blue","cyan","gold","gray","green","magenta","red","white","yellow"];
var guesses=0;
function do_game(){
var n=Math.floor(Math.random()*9);
var color=colors[n];
guess_input_color=prompt("i am thinking of one of these colors:\n\n"+colors+"\n\nWhat color am i thinking of?");
function check_guess(){
alert("Sorry, i don't recognize your color.\n\nPlease try again.");
return false;
alert("Sorry, your guess is not correct!\n\nHint:your color is alphabetically lesser than mine\n\nPlease try again.");
return false;
alert("Sorry, your guess is not correct!\n\nHint:your color is alphabetically higher than mine\n\nPlease try again.");
return false;
document.body.style.backgroundColor = guess_input_color;
document.body.style.backgroundColor = guess_input_color;
alert("Congratulations! You have guessed the color!\n\nIt took you"+guesses+" guesses to finish the game!\n\n")
return true;

Note: both html and js files are in the same directory.

I'm not sure where is the error. Please help me in resolving the issue.

Answer Source

IT should be this

<script type="text/javascript" src="colguess.js"></script>


<script type="text/javascript" src="/colguess.js"></script>

When you reffer '/', it tends to say, looking for the file into the root directory. if files are in the same folder as in html, then no need to use '/'.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download