Moving JavaScript output into other area - javascript

I'm having trouble moving my JavaScript output (start) from the black box into the grey box. I'm not entirely sure what to put into the functions (moveRight and moveLeft) to get the output to move from one to another.
I've tried searching up a solution but was not able to find one. I'm sure there is a nicer way to present this code but I'm still currently learning the basics. Thank you.
function start() {
var txt;
var person = prompt("Please enter your name:", "");
if (person == null || person == "") {
txt = "User cancelled the prompt.";
} else {
txt = person;
}
document.getElementById("text").innerHTML = txt;
}
function moveRight(start) {
}
function moveLeft(start) {
}
.blackbox {
width: 250px;
height: 125px;
background: #000000;
float: left;
color: white;
text-align: center;
height: 90px;
line-height: 90px;
}
.greybox {
width: 250px;
height: 125px;
background: #323232;
float: left;
text-align: center;
height: 90px;
line-height: 90px;
}
.button {
position: relative;
float: left;
padding-left: 10px;
}
.part3 {
position: relative;
float: left;
}
<div id="part3">
<button type="button" onclick="start()">Start</button>
<button type="reset">Clear</button><br><br><br>
<div class="part3">
<div class="blackbox" id="text"></div>
<div class="button">
<br>
<button type="button" onclick="moveRight(start)">--></button><br><br>
<button type="button" onclick="moveLeft(start)"><--</button>
</div>
<br><br>
<div class="greybox" id="name"></div>
</div>
</div>

This code makes the buttons swap the value between the black and gray boxes
var txt;
function start() {
var person = prompt("Please enter your name:", "");
if (person == null || person == "") {
txt = "User cancelled the prompt.";
} else {
txt = person;
}
document.getElementById("text").innerHTML = txt;
}
function moveRight() {
document.getElementById('name').innerHTML = txt;
document.getElementById('text').innerHTML = '';
}
function moveLeft() {
document.getElementById('text').innerHTML = txt;
document.getElementById('name').innerHTML = '';
}
.blackbox{
width:250px;
height:125px;
background:#000000;
float: left;
color: white;
text-align: center;
height: 90px;
line-height: 90px;
}
.greybox{
width:250px;
height:125px;
background:#323232;
float: left;
text-align: center;
height: 90px;
line-height: 90px;
}
.button{
position: relative;
float: left;
padding-left: 10px;
}
.part3{
position: relative;
float: left;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
<meta charset="UTF-8">
</head>
<body>
<div id="part3">
<button type="button" onclick="start()">Start</button>
<button type="reset">Clear</button><br><br><br>
<div class="part3">
<div class="blackbox" id="text"></div>
<div class="button">
<br>
<button type="button" onclick="moveRight()" >--></button><br><br>
<button type="button" onclick="moveLeft()" ><--</button>
</div>
<br><br>
<div class="greybox" id="name"></div>
</div>
</div>
</body>
</html>

Related

How To Reload The Web Page Using A Button In JavaScript

i'm presently working on a gitHub battle game with JavaScript manipulations. Please, how can i make the "PLAY AGAIN" button restart the game. (Starting All Over Again)
I also want to make the "DIV WITH CONTROL-BUTTON ID" display as block only if data fetch from API was successful.... Thanks
MY CODE IS BELOW:
"use strict";
let user = document.getElementsByClassName('github-username'),
player1 = document.getElementById('player-one'),
player2 = document.getElementById('player-two'),
form1 = document.getElementById('form1'),
form2 = document.getElementById('form2'),
cont1 = document.getElementById('continue1'),
cont2 = document.getElementById('continue2'),
reSelect = document.getElementById('reselect-players'),
playAgain = document.getElementById('play-again'),
initiate = document.getElementById('initiate-battle');
// Function that activate the start button
function getStarted() {
let startPage = document.getElementById('startPage'),
startBtn = document.getElementById('get-started-button');
startBtn.onclick = function() {
startPage.style.display = "none";
player1.style.display = "block";
};
};
getStarted();
// Function that initiates player 1 input
function firstForm() {
player1.style.display = "none";
player2.style.display = "block";
return false;
};
// Function that initiates player 2 input
function secondForm() {
let confirmPage = document.getElementById('confirm-page');
player2.style.display = "none";
confirmPage.style.display = "block";
// Function that fetches users data from input
function fetchUsers() {
let user1, user2;
fetch("https://api.github.com/users/" + user[0].value)
.then(function(response) {
return response.json();
})
.then(function(data) {
// Log the data to the console
console.log(data);
// Cache the data to a variable
user1 = data;
let myUser1 = document.getElementById('user1-container'),
totalScore = (1 * user1.followers + 1 * user1.following + 0.5 * user1.public_repos);
myUser1.innerHTML = `<ul class="user-info">
<p id="firstPlayer"> Player 1 </p>
<li id="score">Score: <span class="totalScr"> ${totalScore}</span> </li>
<li><img class="avatar" src="${user1.avatar_url}"></li>
<li>Name: ${user1.name} </li>
<li>Username: ${user1.login} </li>
<li>Following: ${user1.following} </li>
<li>Followers: ${user1.followers} </li>
<li>Repository: ${user1.public_repos} </li>
</ul>`;
//Make another API call and pass it into the stream
return fetch("https://api.github.com/users/" + user[1].value)
.then(function(response) {
//Get a JSON object from the response
return response.json();
})
})
.then(function(data) {
//Log the data to the console
console.log(data);
// Cache the data to a variable
user2 = data;
//Now that you have both APIs back, you can do something with the data
let myUser2 = document.getElementById('user2-container'),
totalScore2 = (1 * user2.followers + 1 * user2.following + 0.5 * user2.public_repos);
myUser2.innerHTML = `<ul class="user-info">
<p id="secondPlayer"> Player 2 </p>
<li id="score2">Score: <span class="totalScr"> ${totalScore2}</span> </li>
<li><img class="avatar" src="${user2.avatar_url}"></li>
<li>Name: ${user2.name} </li>
<li>Username: ${user2.login} </li>
<li>Following: ${user2.following} </li>
<li>Followers: ${user2.followers} </li>
<li>Repository: ${user2.public_repos} </li>
</ul>`;
})
};
fetchUsers();
setTimeout(function() {
document.getElementById('control-buttons').style.display = "block";
playAgain.style.display = "none";
}, 1500);
return false;
};
//Function that assign users score and winner
initiate.onclick = function() {
document.getElementById("confirm-players").innerHTML = "Winner";
document.getElementById('score').style.display = "block";
document.getElementById('score2').style.display = "block";
initiate.style.display = "none";
reSelect.style.display = "none";
playAgain.style.display = "block";
let totalScr = document.getElementsByClassName("totalScr"),
totalScr1 = parseFloat(totalScr[0].innerText),
totalScr2 = parseFloat(totalScr[1].innerText);
if (totalScr1 > totalScr2) {
document.getElementById("firstPlayer").innerHTML = "Winner";
document.getElementById("secondPlayer").innerHTML = "Loser";
} else if (totalScr1 < totalScr2) {
document.getElementById("firstPlayer").innerHTML = "Loser";
document.getElementById("secondPlayer").innerHTML = "Winner";
} else {
confirm("IT'S A TIE, PLAY AGAIN");
};
};
reSelect.onclick = function() {
confirmPage.style.display = "none";
player1.style.display = "block";
user[0].value = null;
user[1].value = null;
};
playAgain.onclick = function() {
//Make this function start the game again, following the usual pattern
};
body {
margin: 0;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif, cursive;
background-image: url('images/photo.jpg');
background-size: 100%;
background-repeat: no-repeat;
}
input[type=text] {
-moz-box-sizing: border-box;
box-sizing: border-box;
box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.3);
border: 1px solid #999;
margin: 50px 0 15px;
}
.body-container {
margin: 0;
text-align: center;
}
.body-container p {
font-size: 16px;
padding-bottom: 5px;
}
.head-text {
padding-top: 60px;
margin-bottom: -10px;
font-size: 36px;
}
#confirm-players {
font-size: 30px;
margin: 10px 0 5px;
}
#get-started-button {
font-size: 18px;
font-weight: 10%;
border: none;
width: 150px;
word-spacing: 2px;
border-radius: 5px;
height: 40px;
background-color: green;
color: white
}
.continue-button {
font-size: 18px;
word-spacing: 2px;
border: none;
width: 200px;
border-radius: 5px;
height: 40px;
background-color: green;
color: white
}
#get-started-button:hover,
.continue-button:hover,
#initiate-battle:hover {
background-color: darkgreen;
}
.github-username {
width: 65%;
height: 35px;
padding: 10px;
margin: 20px 0 15px;
}
#score,
#score2 {
font-size: 18px;
font-weight: bolder;
display: none;
text-align: center;
}
#player-one,
#player-two {
display: none;
}
#confirm-page,
#winner {
display: none;
margin: 20px 0 10px;
}
#initiate-battle,
#play-again {
font-size: 18px;
border: none;
width: 200px;
border-radius: 5px;
word-spacing: 2px;
letter-spacing: 0.4px;
height: 40px;
background-color: green;
color: white;
margin: 15px auto 5px;
}
#reselect-players {
font-size: 18px;
border: none;
word-spacing: 2px;
letter-spacing: 0.4px;
width: 240px;
border-radius: 5px;
height: 35px;
background-color: cornflowerblue;
color: white;
margin: 10px auto;
}
#control-buttons {
display: none;
}
#reselect-players:hover {
background-color: darkslateblue;
}
.avatar {
border-radius: 50%;
height: 200px;
width: 200px;
}
.myUsers {
display: inline-block;
margin: 0 5px 0 10px;
}
ul {
margin-left: -30px;
}
li {
list-style: none;
padding: 5px;
text-align: left;
border: 1px solid grey;
}
#firstPlayer,
#secondPlayer {
margin-bottom: 0;
}
<DOCTYPE! html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="githstyle.css" type="text/css">
</head>
<body>
<div id="startPage" class="body-container">
<h1 class="head-text">GitHub Challenge</h1>
<p>Some challenges are worth engaging 🤓</p>
<button id="get-started-button">Get Started</button>
</div>
<div id="player-one" class="body-container">
<h1 class="head-text">Player One</h1>
<div class="form-container">
<form id="form1" onsubmit="return firstForm();">
<div>
<input type="text" class="github-username" placeholder="Enter Player's GitHub Username" required>
</div>
<div>
<input type="submit" value="Continue" id="continue1" class="continue-button">
</div>
</form>
</div>
</div>
<div id="player-two" class="body-container">
<h1 class="head-text">Player Two</h1>
<div class="form-container">
<form id="form2" onsubmit="return secondForm()">
<div>
<input type="text" name="" class="github-username" placeholder="GitHub Username" required>
</div>
<div>
<input type="submit" value="Continue" id="continue1" class="continue-button">
</div>
</form>
</div>
</div>
<div id="confirm-page" class="body-container">
<h1 id="confirm-players">Confirm players</h1>
<div id="user1-container" class="myUsers">
</div>
<div id="user2-container" class="myUsers">
</div>
<div id="control-buttons">
<div>
<button id="initiate-battle">Initiate Battle</button>
</div>
<div>
<button id="reselect-players">Reselect Players</button>
</div>
<div>
<button id="play-again">Play Again</button>
</div>
</div>
</div>
<script src="gith.js" type="text/javascript">
</script>
</body>
</html>
Reloading the page using JavaScript is very easy.
You can achieve this by using location.reload()
If you want to achieve reloading using a button, then be sure to add a return false; right after you call location.reload() to prevent bubbling (parents of the button won't know the event occurred).
So, your code will look something like this :
document.getElementById('yourButton').addEventListener('click', function(){
location.reload();
return false;
});
Hope this helps ! :)

Loop through Rounds while calling for New user Selection after each round Javascript

I am working on a Rock Paper Scissors game, and I am stuck on a for concepts. I want the user to select the amount of rounds they want through a textbox. Each time the user clicks on a specific image (rock, paper, or scissors) the computer will randomly compile and this will select and image for the computer. Both user and computer chosen images will display in the center of the page in the red and blue squares. I want this to run in a loop until all rounds are complete and then decide an ultimate winner. I am getting lost on how I will make my Loop call for the function where I am having the user select an image, and do this until cpu or user wins. All I am looking for is a bit of guidance as to why I can't figure out how to call for the users selection and then chose a user selection, and repeat this process to completion.
function startGame() {
document.getElementById("gameInfo").style.display = "contents";
}
function clearGame() {
document.getElementById("gameInfo").style.display = "none";
document.getElementById("cpu").src = "";
document.getElementById("user").src = "";
document.getElementById("winner").innerHTML = "";
document.getElementById("userDisplay").innerHTML = "";
document.getElementById("userName").value = "";
}
function displayName() {
var txtName = document.getElementById("userName").value;
document.getElementById("userDisplay").innerHTML = txtName;
}
/*function roundNumber(input) {
var total = document.getElementById("roundChoice").value;
//compSelection(total.value);
console.log(total);
}*/
function userPick(input) {
document.getElementById("user").src = input.src;
roundNumber(input.id);
console.log(input.id);
}
function roundNumber(uInput) {
var total;
var element = document.getElementById("roundChoice").value;
if (element != null) {
total = element.value;
document.getElementById("roundChoice").value = "Let's Begin";
} else {
document.getElementById("roundChoice").value = "Enter Rounds!!!";
}
for (var i = 0; i <= total; i++) {
var compSelect = Math.floor(Math.random() * 3 + 1);
var winner = document.getElementById("winner");
if (compSelect === 1) {
document.getElementById("cpu").src = "images/rock.jpg";
if (uInput === "rock_1") {
winner.innerHTML = "you tied!"
i--;
} else if (uInput === "paper_1") {
winner.innerHTML = "User Wins Round" + i + "!"
} else {
winner.innerHTML = "Computer Wins Round" + i + "!"
}
} else if (compSelect === 2) {
document.getElementById("cpu").src = "images/paper.jpg";
if (uInput === "paper_1") {
winner.innerHTML = "You tied!"
i--;
} else if (uInput === "scissors_1") {
winner.innerHTML("User Wins Round" + i + "!")
} else {
winner.innerHTML = "Computer Wins Round" + i + "!"
}
} else {
document.getElementById("cpu").src = "images/scissors.jpg";
if (uInput === "scissors_1") {
winner.innerHTML = "You tied!"
i--;
} else if (uInput === "rock_1") {
winner.innerHTML = "User Wins Round" + i + "!"
} else {
winner.innerHTML = "computer WIns"
}
}
}
}
body {
font: 80% arial, helvetica, sans-serif;
background: black;
margin: 0;
}
#container {
position: relative;
width: 1100px;
border: solid orange;
border-width: 0 3px;
margin: auto;
overflow: hidden;
height: 78em;
}
#header {
padding: 1em;
position: relative;
overflow: hidden;
}
#title {
color: white;
text-align: center;
font: 280% courier;
text-decoration: none;
text-shadow: 1px 1px 8px orange;
}
p.instruct {
background: grey;
color: white;
text-align: center;
font-size: 120%;
position: relative;
border: solid orange;
border-width: 1px;
padding: .5em 0 .5em 0;
}
#startButton {
float: left;
margin: 0 0 2em 2em;
}
#button {
background: black;
border: dotted orange;
color: orange;
padding: 4px;
}
#clearButton {
margin: 0 0 0 12em;
}
#newButton {
background: black;
border: dotted orange;
color: orange;
padding: 4px;
}
#modifiedGame {
float: right;
margin: 0 2em 2em 0;
}
#newGameBtn {
background: black;
border: dotted red;
color: red;
padding: 4px;
}
#nameInput {
text-align: center;
margin: 3em 0 1em 0;
}
#userName {
text-align: center;
background: black;
border: dotted orange;
padding: 4px;
}
#submitName {
margin: 0 0 5em 39em;
}
#rounds {
clear: both;
text-align: center;
margin: 0;
}
#roundChoice {
text-align: center;
padding: 4px;
border: dotted orange;
background: black;
}
#enterRounds {
margin: 1em 0 2em 39.5em;
}
p.winner {
background: grey;
color: white;
/*clear: both;*/
}
::placeholder {
color: orange;
}
input,
select,
textarea {
color: orange;
}
#images,
p {
clear: both;
color: white;
}
#images {
float: left;
}
#images2 {
float: right;
}
#cpuNameTag {
text-align: center;
color: white;
margin: 0 0 0 45em;
}
#cpuNameTag2 {
color: white;
float: left;
}
#paper_1 {
width: 80px;
height: 80px;
}
#paper_2 {
width: 80px;
height: 80px;
}
#rock_1 {
width: 80px;
height: 80px;
}
#rock_2 {
width: 80px;
height: 80px;
}
#scissors_1 {
width: 80px;
height: 80px;
}
#scissors_2 {
width: 80px;
height: 80px;
}
#rock {
float: left;
}
#paper {
float: left;
}
#scissors {
float: left;
}
#rock2 {
float: right;
}
#scissors2 {
float: right;
}
#paper2 {
float: right;
}
#user_displayed_choice {
background-color: red;
width: 150px;
height: 150px;
float: right;
}
#cpu_displayed_choice {
clear: both;
background-color: blue;
width: 150px;
height: 150px;
float: right;
}
#displayed_choices {
margin: 0 31em 0 0;
}
#user {
width: 100px;
height: 100px;
}
#cpu {
width: 100px;
height: 100px;
}
#gameInfo {
display: none;
}
h4 {
color: orange;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="description" content="CSS intro" />
<meta name="keywords" content="" />
<meta name="author" content="" />
<title>Rock Paper Scissors</title>
<link href="rps.css" rel="stylesheet" type="text/css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript" src="rps.js"></script>
</head>
<body>
<div id="container">
<div id="header">
<h1 id="title"><b>Welcome </b><br><b>to</b> <br><b>Rock Paper Scissors!</b></h1>
</div>
<!--Instructions for game-->
<p class="instruct">Ready to attempt a game of Rock, Paper, Scissors? Select the start button, and then choose the amount of rounds you want to play. Ties in each round will not count towards total rounds. If a tie is present at the end of all the rounds, one final overtime
round will decide the winner. If you dare, try our harder version by beating the computer to unlock.</p>
<!--Buttons for Start, Clear, and Harder Game-->
<div id="modifiedGame">
<input type="button" id="newGameBtn" onclick="newGame" value="Want to try a harder game?">
</div>
<div id="startButton">
<input type="button" id="button" onclick="startGame()" value="Start Game">
</div>
<section id="gameInfo">
<div id="clearButton">
<input type="button" id="newButton" onclick="clearGame()" value="Clear Game">
</div>
<!--^^^-->
<!--Name Input, Round Input-->
<div id="nameInput">
<input type="text" id="userName" placeholder="What is your name?" autofocus required>
</div>
<div id="submitName">
<input type="button" id="nameButton" value="Secure Name" onclick="displayName(this)">
</div>
<div id="rounds">
<input type="text" id="roundChoice" placeholder="Enter # of Rounds" autofocus required>
</div>
<div id="enterRounds">
<input type="button" id="roundButton" value="Set Rounds" onclick="roundNumber(this)">
</div>
<div id="cpuNameTag2">
<h4 id="userDisplay" value=""></h4>
</div>
<div id="cpuNameTag">
<h4>CPU Chooses:</h4>
</div>
<!--Clickable Images for User to Choose. Some Displayed by CPU name to show what CPU Chose after User-->
<div id="images">
<div id="rock">
<img src="images/rock.jpg" alt="rock" id="rock_1" onclick="userPick(this)">
</div>
<div id="paper">
<img src="images/paper.jpg" alt="paper" id="paper_1" onclick="userPick(this)">
</div>
<div id="scissors">
<img src="images/scissors.jpg" alt="scissors" id="scissors_1" onclick="userPick(this)">
</div>
</div>
<div id="images2">
<div id="scissors2">
<img src="images/scissors.jpg" alt="scissors" id="scissors_2">
</div>
<div id="paper2">
<img src="images/paper.jpg" alt="paper" id="paper_2">
</div>
<div id="rock2">
<img src="images/rock.jpg" alt="rock" id="rock_2">
</div>
</div>
<div id="displayed_choices">
<div id="cpu_displayed_choice">
<img id="cpu" src="">
</div>
<div id="user_displayed_choice">
<img id="user" src="">
</div>
</div>
<h1 id="winner"></h1>
</section>
</div>
</body>
</html>
Here you have a working example without the for loop, using 3 global variables (currentRound, totalRounds and wins).
var currentRound = -1;
var totalRounds = -1;
var wins = -1;
function startGame() {
document.getElementById("gameInfo").style.display = "contents";
}
function clearGame() {
document.getElementById("gameInfo").style.display = "none";
document.getElementById("cpu").src = "";
document.getElementById("user").src = "";
document.getElementById("winner").innerHTML = "";
document.getElementById("userDisplay").innerHTML = "";
document.getElementById("userName").value = "";
}
function displayName() {
var txtName = document.getElementById("userName").value;
document.getElementById("userDisplay").innerHTML = txtName;
}
function setRounds() {
var value = document.getElementById("roundChoice").value;
if (value) {
totalRounds = parseInt(value);
currentRound = 0;
wins = 0;
document.getElementById("winner").innerHTML = "Let's Begin";
} else {
document.getElementById("roundChoice").value = "Enter Rounds!!!";
totalRounds = -1;
}
}
function userPick(input) {
if (totalRounds < 0) {
alert("Enter Rounds!!!");
return;
}
if (currentRound >= totalRounds) {
alert("Rounds Finished! Enter Rounds again!!!");
return;
}
//console.log(currentRound + "," + totalRounds)
document.getElementById("user").src = input.src;
currentRound++;
roundNumber(input.id);
}
function roundNumber(uInput) {
var compSelect = Math.floor(Math.random() * 3 + 1);
var winner = document.getElementById("winner");
var i = currentRound + 1;
if (compSelect === 1) {
document.getElementById("cpu").src = "https://image.freepik.com/iconos-gratis/rock-n-roll-gesto-simbolo-de-la-mano-esbozado_318-72191.jpg";
if (uInput === "rock_1") {
winner.innerHTML = "you tied!"
currentRound--;
} else if (uInput === "paper_1") {
wins++;
winner.innerHTML = "User Wins Round " + i + "!"
} else {
winner.innerHTML = "Computer Wins Round " + i + "!"
}
} else if (compSelect === 2) {
document.getElementById("cpu").src = "https://i.pinimg.com/originals/7c/58/78/7c58781da79c7e9b089f206a1ad7b9b5.png";
if (uInput === "paper_1") {
winner.innerHTML = "You tied!"
currentRound--;
} else if (uInput === "scissors_1") {
wins++;
winner.innerHTML = "User Wins Round " + i + "!"
} else {
winner.innerHTML = "Computer Wins Round " + i + "!"
}
} else {
document.getElementById("cpu").src = "https://image.flaticon.com/icons/png/128/164/164986.png";
if (uInput === "scissors_1") {
winner.innerHTML = "You tied!"
currentRound--;
} else if (uInput === "rock_1") {
wins++;
winner.innerHTML = "User Wins Round " + i + "!"
} else {
winner.innerHTML = "computer WIn " + i + "!"
}
}
if (currentRound == totalRounds) {
alert(totalRounds + " Finished:\n"
+ "- wins: " + wins + "\n"
+ "- looses: " + (totalRounds - wins))
}
}
body {
font: 80% arial, helvetica, sans-serif;
background: black;
margin: 0;
}
input[type=button],
#images img {
cursor: pointer;
}
#container {
position: relative;
width: 1100px;
border: solid orange;
border-width: 0 3px;
margin: auto;
overflow: hidden;
height: 78em;
}
#header {
padding: 1em;
position: relative;
overflow: hidden;
}
#title {
color: white;
text-align: center;
font: 280% courier;
text-decoration: none;
text-shadow: 1px 1px 8px orange;
}
p.instruct {
background: grey;
color: white;
text-align: center;
font-size: 120%;
position: relative;
border: solid orange;
border-width: 1px;
padding: .5em 0 .5em 0;
}
#startButton {
float: left;
margin: 0 0 2em 2em;
}
#button {
background: black;
border: dotted orange;
color: orange;
padding: 4px;
}
#clearButton {
margin: 0 0 0 12em;
}
#newButton {
background: black;
border: dotted orange;
color: orange;
padding: 4px;
}
#modifiedGame {
float: right;
margin: 0 2em 2em 0;
}
#newGameBtn {
background: black;
border: dotted red;
color: red;
padding: 4px;
}
#nameInput {
text-align: center;
margin: 3em 0 1em 0;
}
#userName {
text-align: center;
background: black;
border: dotted orange;
padding: 4px;
}
#submitName {
margin: 0 0 5em 39em;
}
#rounds {
clear: both;
text-align: center;
margin: 0;
}
#roundChoice {
text-align: center;
padding: 4px;
border: dotted orange;
background: black;
}
#enterRounds {
margin: 1em 0 2em 39.5em;
}
p.winner {
background: grey;
color: white;
/*clear: both;*/
}
::placeholder {
color: orange;
}
input,
select,
textarea {
color: orange;
}
#images,
p {
clear: both;
color: white;
float: left;
}
#images2 {
float: right;
}
#cpuNameTag {
text-align: center;
color: white;
margin: 0 0 0 45em;
}
#cpuNameTag2 {
color: white;
float: left;
}
#paper_1 {
width: 80px;
height: 80px;
}
#paper_2 {
width: 80px;
height: 80px;
}
#rock_1 {
width: 80px;
height: 80px;
}
#rock_2 {
width: 80px;
height: 80px;
}
#scissors_1 {
width: 80px;
height: 80px;
}
#scissors_2 {
width: 80px;
height: 80px;
}
#rock {
float: left;
}
#paper {
float: left;
}
#scissors {
float: left;
}
#rock2 {
float: right;
}
#scissors2 {
float: right;
}
#paper2 {
float: right;
}
#user_displayed_choice {
background-color: red;
width: 150px;
height: 150px;
float: right;
}
#cpu_displayed_choice {
clear: both;
background-color: blue;
width: 150px;
height: 150px;
float: right;
}
#displayed_choices {
margin: 0 31em 0 0;
}
#user {
width: 100px;
height: 100px;
}
#cpu {
width: 100px;
height: 100px;
}
#gameInfo {
display: none;
}
h4 {
color: orange;
}
#winner {
text-align: center;
color: white;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="description" content="CSS intro" />
<meta name="keywords" content="" />
<meta name="author" content="" />
<title>Rock Paper Scissors</title>
<link href="rps.css" rel="stylesheet" type="text/css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript" src="rps.js"></script>
</head>
<body>
<div id="container">
<div id="header">
<h1 id="title"><b>Welcome </b><br><b>to</b> <br><b>Rock Paper Scissors!</b></h1>
</div>
<!--Instructions for game-->
<p class="instruct">Ready to attempt a game of Rock, Paper, Scissors? Select the start button, and then choose the amount of rounds you want to play. Ties in each round will not count towards total rounds. If a tie is present at the end of all the rounds, one final overtime
round will decide the winner. If you dare, try our harder version by beating the computer to unlock.</p>
<!--Buttons for Start, Clear, and Harder Game-->
<div id="modifiedGame">
<input type="button" id="newGameBtn" onclick="newGame" value="Want to try a harder game?">
</div>
<div id="startButton">
<input type="button" id="button" onclick="startGame()" value="Start Game">
</div>
<section id="gameInfo">
<div id="clearButton">
<input type="button" id="newButton" onclick="clearGame()" value="Clear Game">
</div>
<!--^^^-->
<!--Name Input, Round Input-->
<div id="nameInput">
<input type="text" id="userName" placeholder="What is your name?" autofocus required>
</div>
<div id="submitName">
<input type="button" id="nameButton" value="Secure Name" onclick="displayName(this)">
</div>
<div id="rounds">
<input type="text" id="roundChoice" placeholder="Enter # of Rounds" autofocus required>
</div>
<div id="enterRounds">
<input type="button" id="roundButton" value="Set Rounds" onclick="setRounds()">
</div>
<div id="cpuNameTag2">
<h4 id="userDisplay" value=""></h4>
</div>
<div id="cpuNameTag">
<h4>CPU Chooses:</h4>
</div>
<!--Clickable Images for User to Choose. Some Displayed by CPU name to show what CPU Chose after User-->
<div id="images">
<div id="rock">
<img src="https://image.freepik.com/iconos-gratis/rock-n-roll-gesto-simbolo-de-la-mano-esbozado_318-72191.jpg" alt="rock" id="rock_1" onclick="userPick(this)">
</div>
<div id="paper">
<img src="https://i.pinimg.com/originals/7c/58/78/7c58781da79c7e9b089f206a1ad7b9b5.png" alt="paper" id="paper_1" onclick="userPick(this)">
</div>
<div id="scissors">
<img src="https://image.flaticon.com/icons/png/128/164/164986.png" alt="scissors" id="scissors_1" onclick="userPick(this)">
</div>
</div>
<div id="images2">
<div id="scissors2">
<img src="https://image.flaticon.com/icons/png/128/164/164986.png" alt="scissors" id="scissors_2">
</div>
<div id="paper2">
<img src="https://i.pinimg.com/originals/7c/58/78/7c58781da79c7e9b089f206a1ad7b9b5.png" alt="paper" id="paper_2">
</div>
<div id="rock2">
<img src="https://image.freepik.com/iconos-gratis/rock-n-roll-gesto-simbolo-de-la-mano-esbozado_318-72191.jpg" alt="rock" id="rock_2">
</div>
</div>
<div id="displayed_choices">
<div id="cpu_displayed_choice">
<img id="cpu" src="">
</div>
<div id="user_displayed_choice">
<img id="user" src="">
</div>
</div>
<h1 id="winner"></h1>
</section>
</div>
</body>
</html>

Creating a function to be called again and again

I want to create a simple text game of choices of sorts where you always have two choices and depending on your choice, something is displayed and the current content disappears. My problem is each of the choices are different so i can't figure out a way to not repeat myself again and again in the javascript code.
HTML :
<!Doctype html>
<html>
<head>
<script type="text/javascript" src="jquery-2.1.4.min.js"></script>
<link rel="stylesheet" href="style.css" type="text/css"/>
<title>Game</title>
</head>
<body>
<div id="console">
<div class="storyCard" id="start">
<p class="q">Some stuff.
<p class="a">getup</p>
<p class="a">sleep</p>
</div>
<div class="storyCard" id="getup">
<p class="q">Something happened</p>
<p class="a">do this</p>
<p class="a">do that</p>
</div>
<div class="storyCard" id="sleep">
<p class="q">something else happened</p>
<p class="a">do something</p>
<p class="a">do something else</p>
</div>
<!--and there will be a lot of such storyCards based on the choices.-->
</div>
<script type="text/javascript" src="js.js"></script>
</body>
</html>
CSS :
body {
margin: 0 auto;
align-content: center;
font-family: 'Open Sans', sans-serif;
font-weight: 400;
}
#console {
width: 100%;
}
.storyCard {
min-width: 100px;
max-width: 600px;
background-color: rgba(0, 0, 0, 0.51);
box-shadow: 1px 1px 7px;
padding: 50px;
color: white;
margin: 0 auto;
border-radius: 4px;
display: none;
}
#start {
display: block;
}
.storyCard .a {
background-color: dodgerblue;
border-bottom-color: dodgerblue;
border-top-color: white;
border-left-color: white;
border-right-color: dodgerblue;
padding: 10px;
text-align: center;
color: white;
width: 30%;
display: inline;
margin: 0 auto;
box-shadow: 1px 1px 7px black;
float: right;
cursor: pointer;
}
.storyCard .a:hover {
background-color: white;
color: black;
}
}
Javascript :
document.querySelector('#console').addEventListener('click', function (e) {
var answer = e.target.textContent;
switch (answer) {
case 'getup':
e.target.parentNode.style.display = 'none';
document.querySelector('#getup').style.display = 'block';
break;
case 'sleep':
e.target.parentNode.style.display = 'none';
document.querySelector('#sleep').style.display = 'block';
break;
case 'do this':
e.target.parentNode.style.display = 'none';
/*display another content like above*/
case 'do that':
/*hide the current content again and display another content and add more cases*/
}, false);
I assume that the question must defined in html like your sample. There are many others way to do this better.
You can use class name to specify next question.
document.addEventListener('click', function (e) {
var target = e.target;
if (target.className.match('answer')) {
var nextQuestionId = target.className.replace('answer ', '');
hideAllStoryCards();
showStoryCard(nextQuestionId);
}
});
function hideAllStoryCards () {
var i, elm, elms = document.getElementsByClassName('storyCard');
for (i = 0; i < elms.length; i++) {
elm = elms[i];
elm.style.display = 'none';
}
}
function showStoryCard (id) {
var storyCard = document.getElementById(id);
storyCard.style.display = 'block';
}
hideAllStoryCards();
showStoryCard('first-question');
<div id="console">
<div class="storyCard" id="first-question">
<p class="q">Are you hungry?</p>
<p class="answer what-do-you-want-to-eat">yes</p>
<p class="answer may-i-help-you">no</p>
</div>
<div class="storyCard" id="what-do-you-want-to-eat">
<p class="q">Some stuff.</p>
<p class="answer NEXT_QUESTION_ID">a pie</p>
<p class="answer ANOTHER_QUESTION_ID">a buger</p>
</div>
<div class="storyCard" id="may-i-help-you">
<p class="q">Some stuff.</p>
<p class="answer NEXT_QUESTION_ID">bye</p>
<p class="answer ANOTHER_QUESTION_ID">bye again</p>
</div>
</div>
You can try something like performAction(e, '#getup'); - a generalized method with parameters, in this link.
Please refer below for the code:
HTML:
<div id="console">
<div class="storyCard" id="start">
<p class="q">Some stuff.</p>
<p class="a">getup</p>
<p class="a">sleep</p>
</div>
<div class="storyCard" id="getup">
<p class="q">Something happened</p>
<p class="a">do this</p>
<p class="a">do that</p>
</div>
<div class="storyCard" id="sleep">
<p class="q">something else happened</p>
<p class="a">do something</p>
<p class="a">do something else</p>
</div>
<!--and there will be a lot of such storyCards based on the choices.-->
</div>
CSS:
body {
margin: 0 auto;
align-content: center;
font-family: 'Open Sans', sans-serif;
font-weight: 400;
}
#console {
width: 100%;
}
.storyCard {
min-width: 100px;
max-width: 600px;
background-color: rgba(0, 0, 0, 0.51);
box-shadow: 1px 1px 7px;
padding: 50px;
color: white;
margin: 0 auto;
border-radius: 4px;
display: none;
}
#start {
display: block;
}
.storyCard .a {
background-color: dodgerblue;
border-bottom-color: dodgerblue;
border-top-color: white;
border-left-color: white;
border-right-color: dodgerblue;
padding: 10px;
text-align: center;
color: white;
width: 30%;
display: inline;
margin: 0 auto;
box-shadow: 1px 1px 7px black;
float: right;
cursor: pointer;
}
.storyCard .a:hover {
background-color: white;
color: black;
}
JS:
document.querySelector('#console').addEventListener('click', function(e) {
var answer = e.target.textContent;
switch (answer) {
case 'getup':
performAction(e, '#getup');
break;
case 'sleep':
performAction(e, '#sleep');
break;
case 'do this':
performAction(e, '#getup'); /**Use any 'id' or target of your choice.*/
/*display another content like above*/
break;
case 'do that':
performAction(e, '#getup'); /*Use any 'id' or target of your choice.*/
/*hide the current content again and display another content and add more cases*/
break;
}
}, false);
function performAction(event, target) {
event.target.parentNode.style.display = 'none';
document.querySelector(target).style.display = 'block';
}
You need to separate your data from your UI.
Your data could be something simple like this:
var stories;
function StoryCard(q, option1, option2) {
this.q = q
this.option1 = option1;
this.option2 = option2;
}
function displayStory(storyCard) {
document.getElementById('q').innerHTML = storyCard.q;
document.getElementById('option1').innerHTML = storyCard.option1;
document.getElementById('option2').innerHTML = storyCard.option2;
}
Your "console" UI could change to something more like this:
<div id="console">
<div class="storyCard" id="start">
<p class="q" id="q"> </p>
<p class="a" id="option1"> </p>
<p class="a" id="option2"> </p>
</div>
</div>
Your click function may be more like this:
document.querySelector('#console').addEventListener('click', function (e) {
var answer = e.target.id;
switch (answer) {
default: // for when they click within the div, but not on an option
break;
case 'option1':
case 'option2':
var story = stories[e.target.innerHTML];
if (null != story) {
displayStory(story);
}
break;
}
}, false);
You would set up your stories perhaps in an onload:
function init() {
stories = { "start": new StoryCard("Some stuff", "getup", "sleep")
, "getup": new StoryCard("Something happened", "do this", "do that")
, "sleep": new StoryCard("something else happened", "do something", "do something else")
};
displayStory(stories["start"]);
}

Trying to change colour of a button to show which images is displayed with javascript

I'm trying to change colour of a button to show which images is displayed with JavaScript. Something similar to :Active in CSS. I've been looking for hours, I've managed to change just about every other element on the page except for the one I actually want to change, all I need is to change the background color of the clicked button and then revert back to original color a different button is clicked. Any help would be much appreciated.
<! doctype html>
<html>
<head>
<title>Task 2</title>
<!--styles-->
<style>
body {
margin: 0;
background-color: mediumpurple;
}
header {
margin: auto;
width: 90%;
background-color: orangered;
height: 50px;
text-align: center;
}
#content {
width: 80%;
background-color: green;
margin: auto;
}
nav {
float: left;
background-color: greenyellow;
width: 30%;
height: 750px;
text-align: center;
}
#pictureFrame {
float: left;
width: 70%;
height: 750px;
background-color: deeppink;
}
footer {
margin: auto;
width: 90%;
background-color: orangered;
height: 50px;
text-align: center;
clear: both;
}
.button {
margin-top: 100px;
background-color: white;
border-radius: 20px;
width: 70%;
height: 75px;
}
#img {
margin-top: 19%;
margin-left: 35%;
width: 300px;
height: 300px;
}
</style>
<script type="text/javascript">
function pic1() {
document.getElementById("img").src = "images/starbucks.png";
}
function pic2() {
document.getElementById("img").src = "images/muffin.png";
}
function pic3() {
document.getElementById("img").src = "images/costa.png";
}
</script>
</head>
<body>
<header>
<h1>Coffee</h1>
</header>
<section id="content">
<div id="pictureFrame">
<img src="" id="img" />
</div>
<nav>
<button id="button1" class="button" onclick="pic1()">Starbucks</button>
<br/>
<br/>
<button id="button2" class="button" onclick="pic2()">Muffin Break</button>
<br/>
<br/>
<button id="button3" class="button" onclick="pic3()">Costa</button>
</nav>
</section>
<footer>
<h1>This is a footer</h1>
</footer>
</body>
</html>
By clicking on each button simply change the background of that button with style.background='color'. Also reset the color of other two buttons. Simply create a function to reset the background color.
<script type="text/javascript">
function reset(){
document.getElementById("button1").style.background='white';
document.getElementById("button2").style.background='white';
document.getElementById("button3").style.background='white';
}
function pic1() {
document.getElementById("img").src = "images/starbucks.png";
reset();
document.getElementById("button1").style.background='red';
}
function pic2() {
document.getElementById("img").src = "images/muffin.png";
reset();
document.getElementById("button2").style.background='red';
}
function pic3() {
document.getElementById("img").src = "images/costa.png";
reset();
document.getElementById("button3").style.background='red';
}
</script>
Fiddle : https://jsfiddle.net/tintucraju/6dkt0bs2/

disable jQuery removing javascript tags

Best all,
I'm trying to debug our CMS (what is mostly AJAX) but jQuery removes all the script tags, what makes me unable to debug the JavaScript, how do I disable this behaviour?
I thought I would find it after a simple Google search but no success :(
Thank you,
EDIT
my Page before:
<script>
jQuery(function(){
inter = null;
jQuery('#parse').click(function(){
jQuery('#answer').load(f(),{"POST":jQuery("#POST").val(),"start":((jQuery('#start').val()-1)*10)},function(){
alert("Burrrnnnnnnn")
console.log("Laten we is kijken: " + inter);
clearInterval(inter);
});
inter = setInterval(function(){
jQuery.getJSON("/googlemonster/backend/status-test",function(json){
setProgressBar(json);
});
},200);
return false;
});
});
function
function setProgressBar(obj){
var g;
jQuery("#progress-bar,#progress-text-alt-wrapper").animate({"width":(((g=obj["%"])==0?1:g)*2) + "px"},{queue:false});
jQuery("#progress-text,#progress-text-alt").text(obj["%"] + "% " + obj["status"]);
}
</script>
<style>
#progress-text-alt-wrapper {
height: 30px;
position: absolute;
z-index: 2;
width: 1%;
overflow: hidden;
}
#progress {
border: solid black 1px;
padding: 1px;
text-align: center;
height: 20px;
width: 200px
}
#progress-bar {
background-color: green;
width: 1%;
height: 100%;
}
.progress-bar-text {
padding-top: 3px;
text-align: center;
width: 200px;
position: absolute;
}
#progress-text {
color:green;
}
#progress-text-alt {
color:#eee;
}
</style>
Query:
<input id="POST" type="text" />
<br>
Pagina
<input value="1" id="start"
type="number" />
<br>
<button id="parse">Look</button>
<div>
<div id="progress">
<div id="progress-text-alt-wrapper">
<div class="progress-bar-text" id="progress-text-alt">0% Nothing</div>
</div>
<div class="progress-bar-text" id="progress-text">0% Nothing</div>
<div id="progress-bar"></div>
</div>
</div>
<div id="answer"></div>
The page after
<style>
#progress-text-alt-wrapper {
height: 30px;
position: absolute;
z-index: 2;
width: 1%;
overflow: hidden;
}
#progress {
border: solid black 1px;
padding: 1px;
text-align: center;
height: 20px;
width: 200px
}
#progress-bar {
background-color: green;
width: 1%;
height: 100%;
}
.progress-bar-text {
padding-top: 3px;
text-align: center;
width: 200px;
position: absolute;
}
#progress-text {
color:green;
}
#progress-text-alt {
color:#eee;
}
</style>
Query:
<input id="POST" type="text">
<br>
Pagina
<input value="1" id="start" type="number">
<br>
<button id="parse">Look</button>
<div>
<div id="progress">
<div id="progress-text-alt-wrapper">
<div class="progress-bar-text" id="progress-text-alt">0% Nothing</div>
</div>
<div class="progress-bar-text" id="progress-text">0% Nothing</div>
<div id="progress-bar"></div>
</div>
</div>
<div id="answer"></div>
You are right – it is a feature of jQuery to strip out script tags. You need to use the basic JavaScript methods instead.
See: Can't append <script> element
Scripts will be evaluated first, and then discarded.
http://api.jquery.com/append/
after some research I finnaly could fix the problem thanks to the guys here,
I made a little plugin for jQuery for it, now the script tags are not getting, removed but executed.
(function($){
$.fn.loadDebuggable = function(url){
data = typeof(arguments[1]) == "object"?arguments[1]:{};
success = arguments[2]||typeof(arguments[1]) == "function"?arguments[1]:function(){};
return $.ajax(url,{
"context":this,
"success":[function(data){
var div = document.createElement('DIV');
div.innerHTML = data;
this[0].innerHTML = "";
while (div.firstChild)
{
this[0].appendChild(div.firstChild);
div.removeChild(div.firstChild);
};
},success],
"type":"GET",
"data":data
});
}
})(jQuery);
Thanks,

Categories

Resources