1

We have an assignment where I need to insert an external JavaScript file in a html.

HTML File

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

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];
  while(!finished){
    guess_input_color=prompt("i am thinking of one of these colors:\n\n"+colors+"\n\nWhat color am i thinking of?");
    ++guesses;
    finished=check_guess();
  }
}
function check_guess(){
  if(colors.indexOf(guess_input_color)==-1)
   {
     alert("Sorry, i don't recognize your color.\n\nPlease try again.");
     return false;
   }
  if(color>guess_input_color){
        alert("Sorry, your guess is not correct!\n\nHint:your color is alphabetically lesser than mine\n\nPlease try again.");
         return false;
    }
   if(color<guess_input_color){
        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.

2
  • 2
    Change /colguess.js to colguess.js. The / is saying "go to the root of the server, or drive, then find this file". Commented Aug 24, 2016 at 19:26
  • Thank you @MikeC. i got it now Commented Aug 24, 2016 at 19:27

1 Answer 1

5

IT should be this

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

not

<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 '/'.

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you @Nalin. it's working now, that was dumb of me
Also note that the type attribute is optional in HTML5, so you can just write <script src="colguess.js"></script>
@Christoph yup!! after netscape2 it's not needed anymore !1 you are right. It's optional
@buggenerator It's Learnign phase brah !! :) . Mark this as a answer if it's helpfull !!
Also @NalinAggarwal could you tell me how to change the background color of the page before showing an alert message? (as found in the JS file)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.