8 Replies - 815 Views - Last Post: 11 March 2016 - 10:16 PM

#1 csnetsurfer   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 04-March 16

Can't get my code to work when using a js and css file.

Posted 04 March 2016 - 04:21 AM

I'm very new to Java and have created a few programs already, but this one has two forms in one file and I tried to separate the css and js into a file of their own and it will not work right when I do such. My links are correct and it still will not show correctly. Does anyone know how to fix this problem?

Here are the links I am using:
<link rel="stylesheet" type="text/css" href="GuessingGame.css">
<script type="text/javascript" src="GuessingGame.js"></script>

Attached: Separate files that are not working.

My code below is from the one file, but I would like to separate it into a js and css file.


<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Guessing Game</title>
<link rel="stylesheet" type="text/css" href="GuessingGame.css">
<script type="text/javascript" src="GuessingGame.js"></script>
</head>
<style>
body { background-color: rgb(219,112,147);
background-image: url("images/questionmark.png");
background-repeat: repeat;
font-family: Calibri, San-Serif, Helvetica, Arial;
}
h1 { text-align: center;
color: rgb(219,112,147);
}

#numGuessGame1 { position: relative;
margin-top: -50px;
font-size: 100%;
}

.border { border-bottom: 1px;
border-style: solid;
border-bottom-color: rgba(225,255,255,.9);
margin: -25px auto;
}

.border2 { border-bottom: 1px;
border-style: solid;
border-bottom-color: rgba(225,255,255,.9);
margin: 150px auto;
}

.border3 { border-bottom: 1px;
border-style: solid;
border-bottom-color: rgba(225,255,255,.9);
margin: 210px auto;
}


image { position: relative;
height: 259px;
width: 400px;
}
#fortuneTeller { position: relative;
margin-top: 25px;
}
.flexboxImage { display: flex;
padding-top: 15px;
}
#textBlock { font-size: 20px;
line-height: 150%;
}
#clickMeButton { background: rgb(219,112,147);
color: rgba(255,255,255,1);
border-color: #9ecaed;
border-radius: 18px;
box-shadow: 0 0 10px rgba(158,202,237,1);
outline: none;
height: 36px;
width: 135px;
font-size: 16px;
margin-left:450px;
}

.form { background-color: rgba(225,225,225,1);
font-family: Calibri, San-Serif, Helvetica;
width: 675px;
height: 500px;
border: 3px solid rgba(255,255,255,.8);
border-style: outset;
border-radius: 25px;
margin: 50px auto;
padding: 50px;
}


.form2 { background-color: rgba(225,225,225,1);
font-family: Helvetica, Arial, San-Serif;
width: 675px;
height: 500px;
border: 3px solid rgba(255,255,255,.8);
border-style: outset;
border-radius: 25px;
margin: 50px auto;
padding: 50px;
}

#numGuessGame2 { position: relative;
margin-top: -50px;
font-size: 100%;
}
#inputBox { position: relative;
/*margin-top: 100px;*/
width: 75px;
height: 30px;
margin-left: 10px;
margin-top: 5px;
font-size:24px;
text-align: center;
color: rgb(219,112,147);
}

#submitButton { background: rgb(219,112,147);
color: rgba(255,255,255,1);
border-color: #9ecaed;
border-radius: 18px;
box-shadow: 0 0 10px rgba(158,202,237,1);
outline: none;
height: 35px;
width: 195px;
font-size: 16px;
margin-left:50px;
margin-top: 5px;
}
.posguessHereText { position: relative;
}

.flexboxContainer{ display: flex;
margin-top: 50px;
}
#goAheadText { position: relative;
padding-top: 50px;
}

#restartGameButton { position: relative;
background: rgba(125,125,125,1);
color: rgba(255,255,255,1);
border-color: #9ecaed;
border-radius: 18px;
box-shadow: 0 0 10px rgba(158,202,237,1);
outline: none;
height: 35px;
width: 185px;
font-size: 16px;
margin-left:250px;
}

#posRestartBtn { margin-top: -200px; }

#gameStatus { position: relative;
padding-top: 10px;

}
</style>
<script>

</script>

<body>
<!-- form1 contents holders -->
<form id="form1" class="form" method="get" onsubmit="" name="form1">
<div id="numGuessGame1"><h1 id="h1NumGuessGame"></h1></div>
<p class="border"></p><!-- Horizontal Rule using a border instead-->
<div class="flexboxImage"><!-- flexbox container-->
<div id="fortuneTeller"><img id="idFortuneTeller" src="images/fortuneteller.png" alt="fortuneteller"></div>
<div><p id="textBlock"></p></div>
</div><!-- end of flexbox container-->
<input id="clickMeButton" name="button" type="button" value="Click me!" onclick="startGame()">
<p class="border2"></p><!-- Horizontal Rule using a border instead-->
</form>


<!-- form2 contents holders -->
<form id="form2" class="form2" method="get" onsubmit="" name="form2">
<div id="numGuessGame2">
<h1 id="h1NumGuessGame2"></h1>
</div>
<p class="border"></p><!-- Horizontal Rule using a border instead-->
<div id="posgoAheadText">
<p id="goAheadText"></p>
</div>
<div><p id="numberRemainingText"></p></div>
<div class="flexboxContainer"><!-- flexbox container (Guess text, Inputbox, SubmitButton)-->
<div class="posguessHereText">
<p id="guessHereText"></p>
</div>
<div>
<input id="inputBox" type="text" name="numberInput" value=" " MAXLENGTH="2">
</div>
<div>
<input id="submitButton" name="button" type="button" value="Click to submit" onclick="playerGuesses();">
</div>
</div><!-- End of flexbox container.-->
<div><p id="gameStatus"></p></div>
<p class="border3"></p><!-- Horizontal Rule using a border instead-->
<div id="posRestartBtn">
<input id="restartGameButton" name="button" type="button" value="Restart at anytime" onclick="restartGame();">
</div>
</form>
</body>
<script>

var playerGuess = 0;
var playerNumber = 0;
var computerGuess = 0;
document.getElementById('form2').style.display = "none"; //hides form2
//var playerGuess = document.getElementById("inputBox").value;


//form1
//document.getElementById('form2').style.display = "none"; //hides form2 for reference.
//document.getElementById('form2').style.display = "block"; //shows form2 for reference.
document.getElementById("h1NumGuessGame").innerHTML = "NUMBER GUESSING GAME";
document.getElementById("textBlock").innerHTML = "I'm thinking of a number<br> from"+
" <span style=\"color:rgb(219,112,147)\">1 through 50</span>&#8212"+"<br>"+
"If you can get it in <span style=\"color:rgb(219,112,147)\">6 tries</span>, you"+"<br>"+
" win. If you fail--well, we'll get to"+"<br>"+" that later... <br> <br>"+"Go ahead&#8212 <br>"+
"Click the button and start the game:";


//form2
//Display the heading.
document.getElementById("h1NumGuessGame2").innerHTML = "NUMBER GUESSING GAME";
//Display the Go ahead text.
document.getElementById("goAheadText").innerHTML = "Go ahead&#8212 you've got 6 chances to win.";

//Display Number of Guesses Remaining and what the Computer Guessed.
document.getElementById("numberRemainingText").innerHTML = "Number of guesses remaining: "+
" <span style=\"color:rgb(219,112,147); font-size: 28px;\">"+playerGuess+"</span>" +
"<span style=\"color:rgb(219,112,147); font-size: 28px;\"> "+computerGuess+"</span>";
//Display text on the screen for the inputbox.
document.getElementById("guessHereText").innerHTML = "Enter your guess here: ";
//Display text on the screen for the game status.
document.getElementById("gameStatus").innerHTML = "Game status: ";



/*=================== Player Guesses input ======================*/
/*The player puts a number in the input box and then is the input
passes through the if statements as arguments in showing a result.*/
/*=================================================================*/
function playerGuesses()

{
playerGuess = 0;
document.getElementById('submitButton').addEventListener('click',function()
{
playerGuess = document.getElementById('inputBox').value;
playerGuess = parseFloat( inputBox );
});

//playerGuess == computerGuess;
if (playerGuess.value == computerGuess)

{
alert("Winner!");
}
else
{
alert("Please guess another number!");
}
}

/*=================== Beginning of the Game =======================*/
/*The Click Me button starts the game, the first form dissapears
and the second form appears.*/
/*=================================================================*/
function startGame()
{
var computerGuess = Math.floor(Math.random() * 5) + 1 //Generates a random number from 1 through 5.
document.getElementById('form1').style.display = "none"; //hides form1
document.getElementById('form2').style.display = "block"; //shows form2

// Display the number of player guesses and the computer's random number.
document.getElementById("numberRemainingText").innerHTML = "Number of guesses remaining: "+
" <span style=\"color:rgb(219,112,147); font-size: 28px;\">"+playerGuess+"</span>" +
"<span style=\"color:rgb(219,112,147); font-size: 28px;\"> "+
"&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspComputer Guess: "+computerGuess+"</span>";

//Call function playerNumber.
playerGuesses();
}

/*=================== Restart the Game Over =======================*/
/*Restart the game by using the window object reload attribute.
Note: This is the same as window.location.reload(true); code.*/
/*=================================================================*/
function restartGame()
{
location.reload(true);
}
</script>


</html>

Attached File(s)



Is This A Good Question/Topic? 0
  • +

Replies To: Can't get my code to work when using a js and css file.

#2 TechnoBear   User is offline

  • Lady A
  • member icon

Reputation: 186
  • View blog
  • Posts: 818
  • Joined: 02-November 11

Re: Can't get my code to work when using a js and css file.

Posted 04 March 2016 - 06:03 AM

Mate, not being funny but this is HTML =P

JS and Java are more like close cousins than actually related...

Anyway, I probably could help better if I could see for sure how the files divided, I at work so can't download your file but if you wanna post your code in [CODE] tags I can have a look.
Was This Post Helpful? 0
  • +
  • -

#3 andrewsw   User is offline

  • RequestedRangeNotSatisfiable
  • member icon

Reputation: 6561
  • View blog
  • Posts: 26,600
  • Joined: 12-December 12

Re: Can't get my code to work when using a js and css file.

Posted 04 March 2016 - 06:29 AM

Moved to Javascript forum.
Was This Post Helpful? 0
  • +
  • -

#4 csnetsurfer   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 04-March 16

Re: Can't get my code to work when using a js and css file.

Posted 10 March 2016 - 11:26 PM

Thank you so much for your help on this! I'm still learning and things are looking up! I really appreciate your help!

I found out that what was happening was that the js file was loading first, css and html were loading after the java script, so what I did was put the relational tag near the body closing tag and everything worked again. Everything works well now accept that I would like to create a listener event for if the person presses enter to fire the submit button, so that it will submit what ever is in the input box. Not sure how to go about doing this.

Here is my final submit on what I came up with for the guess a number game as a project:

/*============= Load the CSS and HTML First ================
Append the Child Element Javascript to the HTML Body, so
that the HTML and CSS load first and the js file loads last.
============================================================*/
function downloadJSAtonload()
{
var element = document.createElement("script");
element.src = "GuessingGame.js";
document.body.appendChild(element);
document.getElementById('form2').style.display = "none"; //hides form2 for reference.
}
if (window.addEventListener)
window.addEventListener("load", downloadJSAtonload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtonload);
else window.onload = downloadJSAtonload;

/*==================== Global Initiations ===================
Global variables and initiation scripts. Load the header,
and all the other content that needs to be seen when the
forms load. Allow the computer to guess randomly right away.
=============================================================*/
var playerGuess = 6;
var computerGuess = 0;
var gameStatus = 0;
var gamesRemaining = 6;
var computerGuess = Math.floor(Math.random() * 50) + 1; //Generates a random number from 1 through 5.
"use strict";
document.title = "Guessing Game";
playerGuess = parseInt(document.getElementById('inputBox').value);

//form1 (initialized content)
document.getElementById("form1").autocomplete = "off";
document.getElementById('restartGameButton').onclick="startGame();";
document.getElementById("h1NumGuessGame").innerHTML = "NUMBER GUESSING GAME";
document.getElementById("textBlock").innerHTML= "I'm thinking of a number<br> from"+
" <span style=\"color:rgb(219,112,147)\">1 through 50</span>&#8212"+"<br>"+
"If you can get it in <span style=\"color:rgb(219,112,147)\">6 tries</span>, you"+"<br>"+
" win. If you fail--well, we'll get to"+"<br>"+" that later... <br> <br>"+"Go ahead&#8212 <br>"+
"Click the button and start the game:";

//form2 (initialized content)
document.getElementById("inputBox").maxLength = "2";
document.getElementById("form2").autocomplete = "off";
document.getElementById('restartGameButton').onclick="restartGame();";
document.getElementById("h1NumGuessGame2").innerHTML = "NUMBER GUESSING GAME";
document.getElementById("goAheadText").innerHTML = "Go ahead&#8212 you've got 6 chances to win.";

document.getElementById("numberRemainingText").innerHTML = "Number of guesses remaining: "+
" <span style=\"color:rgb(219,112,147); font-size: 28px;\">"+playerGuess+"</span>"+
"<span style=\"color:rgb(219,112,147); font-size: 28px;\"> "+computerGuess+"</span>";

document.getElementById("guessHereText").innerHTML = "Enter your guess here: ";
document.getElementById("gameStatus").innerHTML = "Game status: "+
"<span style=\"color:rgb(219,112,147)\">(Guess a number 1 - 50)</span>";

/*=================== Beginning of the Game =======================
The Click Me button starts the game, the first form dissapears
and the second form appears. You get all the beginning stats:
Player Guesses, gamesRemaining = remaining tries.
=================================================================*/
document.getElementById("clickMeButton").onclick = function startGame()
{
document.getElementById('form1').style.display = "none";
document.getElementById('form2').style.display = "block";

document.getElementById("numberRemainingText").innerHTML = "Number of guesses remaining: "+
" <span style=\"color:rgb(219,112,147); font-size: 28px;\">"+gamesRemaining+"</span>";
playerGuesses();
};

/*=================== Player Guesses Input ======================
The player puts a number in the input box and then is the input
passes through the if statements as arguments in showing a result.
Set the focus to the input box right away.
=================================================================*/
var playerGuesses = document.getElementById("submitButton").onclick = function playerGuesses()
{
document.getElementById("inputBox").focus();
document.getElementById("submitButton").addEventListener('click', runSwitch);
};

/*====================== Run the Switch =========================
Start off with putting focus on the input box and parsing what
the user inputs as a integer between 1 and 50. The Switch is
based on the inputs that are true for the output on conditions:
isNaN or null, Out of Range, playerGuess less than computerGuess,
playerGuess is greater than computerGuess, and Correct number
guessed. Monitor the number of tries and update the tries for
each time as needed. Note: Winning is different than running out
of turns, but you also have no turns left if you win and the input
box will be grayed out (user cannot enter anymore).
=================================================================*/
function runSwitch()
{
document.getElementById("inputBox").focus();
playerGuess = parseInt(document.getElementById('inputBox').value);
switch (true)
{
case (isNaN(playerGuess)|| playerGuess === null):
triesRemainingUpdates();
document.getElementById("gameStatus").innerHTML += "<br><br>"+
"<span style=\"color:rgb(255,0,0);\">Error! You did not put a number in! "+
" Please try again!</span>"+
"<br> Please put a number in between 1 and 50 (inclusive)";
triesRemaining();
break;

case (playerGuess < 1 || playerGuess > 50):
triesRemainingUpdates();
document.getElementById("gameStatus").innerHTML += "<br>"+
"<span style=\"color:rgb(255,0,0);\">The number you put in is out of range!"+
" Please put a number in between 1 and 50: (inclusive)</span><br>";
triesRemaining();
break;

case (playerGuess > 0 && playerGuess < 51 && playerGuess < computerGuess):
triesRemainingUpdates();
document.getElementById("gameStatus").innerHTML += "<br>"+
"Please guess again! "+
" &nbsp&nbsp&nbsp&nbsp Your guess was: " +playerGuess+
" <span style=\"color:rgb(219,112,147);\">(Please go Higher!)</span><br>";
triesRemaining();
break;

case (playerGuess > 0 && playerGuess < 51 && playerGuess > computerGuess):
triesRemainingUpdates();
gameStatus = document.getElementById("gameStatus").innerHTML += "<br>"+
"Please guess again! "+" &nbsp&nbsp&nbsp&nbsp Your guess was: " +playerGuess+
" <span style=\"color:rgb(219,112,147);\">(Please go Lower!)</span><br>";
triesRemaining();
break;

case (playerGuess === computerGuess ):
winner();

break;
}
}

/*================== Disable the Enter Key ======================
This disables the enter key from being used, because the textbox
will kick the form2 back out to the other form1 if you press the
enter key. We could use an event listener and make the button click?
Another option.
=================================================================*/
function stopRKey(evt)
{
evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (node.type=="text"))
{
return false;
}
}
document.onkeypress = stopRKey;

/*===================== Games Remaining =========================
Check to see the number of guesses remaining and don't allow the
player to play anymore if there are no more guesses remaining.
Disable the input box and tell them the stats.
=================================================================*/
function winner()
{
gamesRemaining = 0;
document.getElementById("numberRemainingText").innerHTML = "Number of guesses remaining: "+
" <span style=\"color:rgb(219,112,147); font-size: 28px;\">"+gamesRemaining+"</span>" +
"<span style=\"color:rgb(219,112,147); font-size: 28px;\"> "+
"&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspComputer Guess: "+computerGuess+"</span>";
document.getElementById("gameStatus").innerHTML += "<br>"+"You guessed the correct number: "+
"<span style=\"color:rgb(219,112,147); font-size: 28px;\">"+
playerGuess+"</span> <span style=\"color:rgb(0,155,0); font-size: 28px;\"> (Winner!)</span> "+
" Tries remaining:<span style=\"color:rgb(219,112,147); font-size: 28px;\"> "+gamesRemaining+
"</span><br> Would you like to play another round? Then please hit the Restart at anytime button!";
document.getElementById('inputBox').disabled = true;
}

/*===================== Games Remaining =========================
Check to see the number of guesses remaining and don't allow the
player to play anymore if there are no more guesses remaining.
Disable the input box and tell them the stats.
=================================================================*/
function triesRemaining()
{
if (gamesRemaining === 0)
{
gamesRemaining = 0;
document.getElementById("gameStatus").innerHTML += "<br>"+
"<br><span style=\"color:rgb(255,0,0); font-size: 28px;\">You have no more tries! (Exit or play again!)</span><br>"+
"<br>Your guess was:<span style=\"color:rgb(219,112,147); font-size: 28px;\"> "+playerGuess+
"</span> Computer Guess:<span style=\"color:rgb(219,112,147); font-size: 28px;\"> "+computerGuess;
document.getElementById('inputBox').disabled = true;
document.getElementById('submitButton').disabled = true;
}
}

/*================= Games Remaining Updates =====================
Check to see the number of guesses remaining and don't allow the
player to play anymore if there are no more guesses remaining.
=================================================================*/
function triesRemainingUpdates()
{
gamesRemaining--;
document.getElementById("numberRemainingText").innerHTML = "Number of guesses remaining: "+
" <span style=\"color:rgb(219,112,147); font-size: 28px;\">"+gamesRemaining;
document.getElementById('inputBox').value = "";
}


/*=================== Restart the Game Over =====================
Restart the game by using the window object reload attribute.
Note: This is the same as window.location.reload(true); code.
=================================================================*/
document.getElementById("restartGameButton").onclick =function restartGame()
{
location.reload(true);
};
Was This Post Helpful? 0
  • +
  • -

#5 csnetsurfer   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 04-March 16

Re: Can't get my code to work when using a js and css file.

Posted 10 March 2016 - 11:46 PM

View PostTechnoBear, on 04 March 2016 - 06:03 AM, said:

Mate, not being funny but this is HTML =P

JS and Java are more like close cousins than actually related...

Anyway, I probably could help better if I could see for sure how the files divided, I at work so can't download your file but if you wanna post your code in [CODE] tags I can have a look.


---------------------------------------------------------------------------------------------------
Hi TechnoBear,

I got everything up and running again and submitted my assignment, things look good on the guessing game that I created.

I tested it using 1-5, but it really is 1-50 in guessing.

Yes, it is HTML, CSS and Java Script. I wish I knew how to code a key down event for if someone uses the enter key to where it would fire the submit button and submit what ever is in the input box. I disabled the keyboard in this version, but it sure would be nice the other way around. Figured you would like my program so I attached it nearly totally completed. One of the stipulations is that I was not allowed to use handler events in my HTML, so I put everything nearly in Java script. It's a nice looking program and if you have any advice, please do! I'm always glad to learn more!
Was This Post Helpful? 0
  • +
  • -

#6 andrewsw   User is offline

  • RequestedRangeNotSatisfiable
  • member icon

Reputation: 6561
  • View blog
  • Posts: 26,600
  • Joined: 12-December 12

Re: Can't get my code to work when using a js and css file.

Posted 11 March 2016 - 02:03 AM

How to use code tags:

Attached Image
Was This Post Helpful? 0
  • +
  • -

#7 TechnoBear   User is offline

  • Lady A
  • member icon

Reputation: 186
  • View blog
  • Posts: 818
  • Joined: 02-November 11

Re: Can't get my code to work when using a js and css file.

Posted 11 March 2016 - 09:31 AM

To have a submit button in HTML it is:

<input type="submit" />

Was This Post Helpful? 0
  • +
  • -

#8 astonecipher   User is offline

  • Senior Systems Engineer
  • member icon

Reputation: 2555
  • View blog
  • Posts: 10,255
  • Joined: 03-December 12

Re: Can't get my code to work when using a js and css file.

Posted 11 March 2016 - 11:20 AM

This would probably be more fitting:


<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src='http://code.jquery.com/jquery-1.12.1.min.js'></script>

</head>
<body>

	<div>
		<input type='text' id='txtTest'>
	</div>
	<div id='contents'></div>
	<script>
		$(document).ready(
			function() {
				$('#txtTest').keypress(
					function(event) {
						if (event.key >= 0 && event.key <= 9) {
							$('#contents').append( '<p>You entered the number ' + event.key + '</p>');
							$('#txtTest').val('');
						} else {
							$('#txtTest').val('');
						}
					});
				});
	</script>

</body>
</html>

Was This Post Helpful? 1
  • +
  • -

#9 felgall   User is offline

  • D.I.C Regular

Reputation: 68
  • View blog
  • Posts: 365
  • Joined: 22-February 14

Re: Can't get my code to work when using a js and css file.

Posted 11 March 2016 - 10:16 PM

Except for rare one line Javascript - you should never place scripts in the head - they all go just before the </body> tag. The rare exceptions are scripts that must run before the page starts to load and most of these are one line of code (either to add a class to the HTML tag to indicate that the necessary level of Javascript is supported for the script to run or to not load the page at all in the current situation such as to break out of frames). The only multi-line code I know of that needs to go in the head is modernizr.js which adds multiple classes to the HTML tag.

Also Google severely penalizes web pages that slow the content loading by loading scripts before the content. Also scripts normally need the page content loaded first in order to interact with it.

So there are plenty of reasons to put all the scripts at the very bottom.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1