How to properly hide cells in a CSS grid? - javascript

I'm new to CSS. I'm trying to create a nice grid that changes based on the user input. Here is my approach to this:
Create the "biggest" grid and set everything to be hidden.
When the user input changes, display the cells that required to be displayed. Also, change the margin accordingly.
I noticed that when I follow that logic, my cells somehow being push in a direction. It almost like the hidden cells still taking space somehow. Is there anyway to avoid this?
Here's my attempt:
'use strict'
let topBtn = document.querySelector("#top-btn");
let greyBar = document.querySelector("#grey-bar");
let topBtnClicked = false;
let gridSelectionBtns = document.querySelectorAll(".grid-selection-btn");
let mediaContainer = document.querySelector("#media-container");
let mediaCells = document.querySelectorAll(".media-cell");
function onTopBtnMouseEvent(ev) {
if (ev.type === "click") {
topBtn.style.opacity = "0.7";
greyBar.style.opacity = "0.7";
topBtnClicked = true;
} else if (ev.type === "mouseover") {
topBtn.style.opacity = "0.7";
} else if (ev.type === "mouseout") {
if (!topBtnClicked) {
topBtn.style.opacity = "0";
}
}
}
function onTopBarMouseEvent(ev) {
if (ev.type === "mouseover") {
} else if (ev.type === "mouseout") {
if (topBtnClicked && !(greyBar.contains(ev.relatedTarget) || (ev.relatedTarget === topBtn))) {
topBtnClicked = false;
topBtn.style.opacity = "0";
greyBar.style.opacity = "0";
}
}
}
function enableMediaCell(cellNumber, isEnable) {
let cell = mediaCells[cellNumber];
if (isEnable) {
cell.style.visibility = "visible";
cell.style.margin = "25px";
cell.style.gridGap = "10px";
} else {
cell.style.visibility = "hidden";
cell.style.margin = "0";
cell.style.gridGap = "0";
}
}
function gridSelectedHandler(type) {
if (!topBtnClicked) {
return;
}
switch (type) {
case 0:
mediaContainer.style.opacity = "1";
enableMediaCell(0, true);
for (let i = 1; i < mediaCells.length; ++i) {
enableMediaCell(i, false);
}
mediaContainer.style.gridTemplateColumns = "repeat(1, 1fr)";
mediaContainer.style.gridTemplateRows = "repeat(1, 1fr)";
break;
case 1:
mediaContainer.style.opacity = "1";
enableMediaCell(0, true);
enableMediaCell(1, true);
for (let i = 2; i < mediaCells.length; ++i) {
enableMediaCell(i, false);
}
mediaContainer.style.gridTemplateColumns = "repeat(2, 1fr)";
mediaContainer.style.gridTemplateRows = "repeat(1, 1fr)";
break;
case 2:
mediaContainer.style.opacity = "1";
for (let i = 0; i < 4; ++i) {
enableMediaCell(i, true);
}
for (let i = 4; i < mediaCells.length; ++i) {
enableMediaCell(i, false);
}
mediaContainer.style.gridTemplateColumns = "repeat(2, 1fr)";
mediaContainer.style.gridTemplateRows = "repeat(2, 1fr)";
break;
case 3:
mediaContainer.style.opacity = "1";
for (let i = 0; i < 6; ++i) {
enableMediaCell(i, true);
}
for (let i = 6; i < mediaCells.length; ++i) {
enableMediaCell(i, false);
}
mediaContainer.style.gridTemplateColumns = "repeat(3, 1fr)";
mediaContainer.style.gridTemplateRows = "repeat(2, 1fr)";
break;
case 4:
mediaContainer.style.opacity = "1";
for (let i = 0; i < mediaCells.length; ++i) {
enableMediaCell(i, true);
}
mediaContainer.style.gridTemplateColumns = "repeat(3, 1fr)";
mediaContainer.style.gridTemplateRows = "repeat(3, 1fr)";
break;
default:
break;
}
}
for (let i = 0; i < gridSelectionBtns.length; ++i) {
gridSelectionBtns[i].addEventListener("click", function() {
gridSelectedHandler(i)
})
}
document.addEventListener('keydown', function(e) {
if (e.key === 'Escape') {
mediaContainer.style.opacity = "0"
}
});
topBtn.onmouseover = topBtn.onmouseout = topBtn.onclick = onTopBtnMouseEvent;
greyBar.onmouseover = greyBar.onmouseout = greyBar.onclick = onTopBarMouseEvent;
body {
background-image: url("../media/gopher_background.jpg");
background-size: cover;
}
#top-btn {
width: 100%;
height: 25px;
opacity: 0;
background-image: url("../media/down-arrow.svg");
background-repeat: no-repeat;
background-position: center;
}
#grey-bar {
background-color: GhostWhite;
width: 100%;
height: 50px;
opacity: 0;
display: flex;
justify-content: center;
}
.grid-selection-btn {
width: 5%;
height: 100%;
margin: 0 1%;
}
#media-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(3, 1fr);
opacity: 0;
min-height: 85vh;
background-color: lightgray;
}
.media-cell {
background-color: lightgray;
visibility: hidden;
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-template-rows: repeat(2, 1fr);
grid-gap: 10px;
margin: 25px;
}
.youtube-btn {
/*background-image: url("../media/youtube-logo.png");*/
background-repeat: no-repeat;
background-position: center;
background-size: contain;
margin: 0 0 0 0;
padding: 0 0 0 0;
}
.reddit-btn {
/*background-image: url("../media/reddit-icon.png");*/
background-repeat: no-repeat;
background-position: center;
background-size: contain;
margin: 0 0 0 0;
padding: 0 0 0 0;
}
.twitter-btn {
/*background-image: url("../media/twitter.png");*/
background-repeat: no-repeat;
background-position: center;
background-size: contain;
margin: 0 0 0 0;
padding: 0 0 0 0;
}
.insta-btn {
/*background-image: url("../media/insta-logo.png");*/
background-repeat: no-repeat;
background-position: center;
background-size: contain;
margin: 0 0 0 0;
padding: 0 0 0 0;
}
<button id="top-btn"></button>
<div id="grey-bar">
<button class="grid-selection-btn">1</button>
<button class="grid-selection-btn">2</button>
<button class="grid-selection-btn">3</button>
<button class="grid-selection-btn">4</button>
<button class="grid-selection-btn">5</button>
</div>
<div id="media-container">
<div class="media-cell">
<button class="youtube-btn"></button>
<button class="reddit-btn"></button>
<button class="insta-btn"></button>
<button class="twitter-btn"></button>
</div>
<div class="media-cell">
<button class="youtube-btn"></button>
<button class="reddit-btn"></button>
<button class="insta-btn"></button>
<button class="twitter-btn"></button>
</div>
<div class="media-cell">
<button class="youtube-btn"></button>
<button class="reddit-btn"></button>
<button class="insta-btn"></button>
<button class="twitter-btn"></button>
</div>
<div class="media-cell">
<button class="youtube-btn"></button>
<button class="reddit-btn"></button>
<button class="insta-btn"></button>
<button class="twitter-btn"></button>
</div>
<div class="media-cell">
<button class="youtube-btn"></button>
<button class="reddit-btn"></button>
<button class="insta-btn"></button>
<button class="twitter-btn"></button>
</div>
<div class="media-cell">
<button class="youtube-btn"></button>
<button class="reddit-btn"></button>
<button class="insta-btn"></button>
<button class="twitter-btn"></button>
</div>
<div class="media-cell">
<button class="youtube-btn"></button>
<button class="reddit-btn"></button>
<button class="insta-btn"></button>
<button class="twitter-btn"></button>
</div>
<div class="media-cell">
<button class="youtube-btn"></button>
<button class="reddit-btn"></button>
<button class="insta-btn"></button>
<button class="twitter-btn"></button>
</div>
<div class="media-cell">
<button class="youtube-btn"></button>
<button class="reddit-btn"></button>
<button class="insta-btn"></button>
<button class="twitter-btn"></button>
</div>
</div>
I have been learning web dev for about 2 weeks now. I realize that my code might not be the best practice. I would love to receive some feedback on that too.

You observed correctly, the hidden elements are still taking space. That is the case with visibility: hidden ... to have an element not be visible or take space on the page at all, you want display: none. The default value for the display attribute of a div is block, so you could use that to make a cell visible in the script.

Related

Remove last character from calculator display

I've added a back button to my calculator with the idea that when someone presses it they can undo if they clicked the wrong number.
I've tried to solve using substr within an if statement in my calculate function but nothing seems to be happening it's as if it's not recording when the user clicks the button. To be honest I'm not sure this is the correct approach!
//Create variable to hold display value, create variable of display area and populate.
let toShow = 0;
let displayValue = 0;
let displayArea = document.getElementById('result-display');
let dataType = document.querySelectorAll('[data-type]');
let operator = "";
let firstNumber = 0;
let secondNumber = 0;
let operatorPressed = false;
let secondNumberCounter = false;
let firstNumberCounter = false;
let buttonNumber = 0;
let decimalCounter = 0;
displayArea.innerHTML = 0;
/* displayArea.innerHTML += displayValue; */
//Basic math functions
add = (firstNumber, secondNumber) => firstNumber + secondNumber;
subtract = (firstNumber, secondNumber) => firstNumber - secondNumber;
multiply = (firstNumber, secondNumber) => firstNumber * secondNumber;
divide = (firstNumber, secondNumber) => firstNumber / secondNumber;
//Take an operator and two numbers and call a math function
operate = (operator, firstNumber, secondNumber) => {
toShow = operator(firstNumber, secondNumber);
return Math.round(toShow * 100) / 100;
};
//Update display with button clicked
const button = document.querySelectorAll('.item');
addEventListener('click', e => {
calculate(e);
});
let calculate = (e) => {
if (e.target.id === "equals" && secondNumber === 0) {
displayArea.innerHTML = "OH HELL NO!";
} else if (e.target.id === "equals") {
decimalCounter = 0;
switch (operator) {
case "add":
secondNumberCounter = false;
return firstNumber = displayArea.innerHTML = operate(add, firstNumber, secondNumber);
case "multiply":
secondNumberCounter = false;
return firstNumber = displayArea.innerHTML = operate(multiply, firstNumber, secondNumber);
case "divide":
secondNumberCounter = false;
return firstNumber = displayArea.innerHTML = operate(divide, firstNumber, secondNumber);
case "subtract":
secondNumberCounter = false;
return firstNumber = displayArea.innerHTML = operate(subtract, firstNumber, secondNumber);
}
}
if (operatorPressed === true && e.target.dataset.type === "number") {
if (secondNumberCounter === false) {
displayArea.innerHTML = null;
}
if (decimalCounter === 0) {
let secondButtonNumber = e.target.innerText;
displayValue = secondButtonNumber;
displayArea.innerHTML += displayValue;
secondNumber = Number(displayArea.innerHTML);
secondNumberCounter = true;
}
} else if (e.target.dataset.type === "nonNumber") {
decimalCounter = 0;
operator = e.target.id;
firstNumber = Number(displayArea.innerText);
operatorPressed = true;
} else {
if (e.target.id === "decimal" && decimalCounter === 0) {
++decimalCounter;
buttonNumber = e.target.innerText;
displayValue = buttonNumber;
displayArea.innerHTML += displayValue;
console.log(buttonNumber);
} else {
buttonNumber = Number(e.target.innerText);
displayValue = buttonNumber;
displayArea.innerHTML += displayValue;
displayArea.innerHTML = Number(displayArea.innerHTML);
}
}
if (e.target.id === "AC") {
secondNumberCounter = false;
operatorPressed = false;
firstNumber = 0;
secondNumber = 0;
buttonNumber = 0;
decimalCounter = 0;
displayArea.innerHTML = 0;
}
}
body {
display: flex;
align-items: center;
justify-content: center;
border: 1px solid black;
flex-direction: row;
width: 100%;
height: 100vh;
}
.container {
display: flex;
align-items: center;
justify-content: center;
background-color: gray;
width: 275px;
height: 450px;
border: 1px solid black;
}
.sub-container {
display: flex;
flex-direction: column;
align-items: center;
height: 95%;
width: 800%;
}
.display {
display: flex;
align-items: center;
justify-content: flex-end;
border: 1px solid white;
width: 80%;
height: 10%;
margin: 5% 0 5% 0;
color: white;
}
#result-display {
margin-right: 8%;
}
.button-grid {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
height: 100%;
width: 80%;
}
.item {
width: 50px;
height: 50px;
border: 1px solid white;
display: flex;
flex-wrap: wrap;
justify-content: center;
align-items: center;
color: black;
}
button {
width: 100%;
height: 100%;
}
footer {
width: 100%;
background-color: gray;
}
Make the calculator work! You’ll need to store the first number that is input into the calculator when a user presses an operator,
and also save which operation has been chosen and then operate() on them when the user presses the “=” key.
<div class="container">
<div class="sub-container">
<div class="display">
<p id="result-display">
</p>
</div>
<div class="button-grid">
<div>
<button class="item" id="7" data-type="number">
7
</button>
</div>
<div>
<button class="item" id="8" data-type="number">
8
</button>
</div>
<div>
<button class="item" id="9" data-type="number">
9
</button>
</div>
<div>
<button class="item" id="divide" data-type="nonNumber">
*/*
</button>
</div>
<div>
<button class="item" id="4" data-type="number">
4
</button>
</div>
<div>
<button class="item" id="5" data-type="number">
5
</button>
</div>
<div>
<button class="item" id="6" data-type="number">
6
</button>
</div>
<div>
<button class="item" id="multiply" data-type="nonNumber">
X
</button>
</div>
<div>
<button class="item" id="1" data-type="number">
1
</button>
</div>
<div>
<button class="item" id="2" data-type="number">
2
</button>
</div>
<div>
<button class="item" id="3" data-type="number">
3
</button>
</div>
<div>
<button class="item" id="subtract" data-type="nonNumber">
-
</button>
</div>
<div>
<button class="item" id="0" data-type="number">
0
</button>
</div>
<div>
<button class="item" id="decimal" data-type="number">
.
</button>
</div>
<div>
<button class="item" id="AC" data-type="nonNumber">
AC
</button>
</div>
<div>
<button class="item" id="add" data-type="nonNumber">
+
</button>
</div>
<div>
<button class="item" id="equals" data-type="nonNumber">
=
</button>
</div>
<div>
<button class="item" id="back" data-type="nonNumber">
<
</button>
</div>
</div>
</div>
</div>
<div>
<!-- User presses back button
preprend displayValue
displayValue remove one
displayArea.innerHTML remove one
let str = 'Mozilla';
let smallStr = str.substr(0, str.length - 1);-->
You can use either The Memento Pattern or The Command Pattern explained here:
How to make a undo/redo function
I ended up solving this using substring. Basically I look for the length of the string in my calculators display then remove the last character.
Code used in an IF Statement:
if (e.target.id === "back") {
displayArea.innerHTML = displayArea.innerHTML.substring(0, displayArea.innerHTML.length - 1);
}

TicTacToe - minimax-function always returns -10 (Javascript)

I'm working on a tictactoe Person vs Person game. As a bonus, we can try to implement a minimax algorithm to play against the computer. After numerous trials and errors, I think I have the function so far, that it goes through the calculation without an error. However, the return value for best Score is always -10, assuming the player and not the computer would win.
I have two problems in the code:
the minimax-function always returns the value -10, assuming the person would win.
I cant play the last turn. In the debugger I can see that my gameData array, that keeps track of the visible field, works normally like so: [0,"X","X","O","X","O","O",7,"X"]. But the arrays player.person and player.computer have already stored the 0 and the 7. This should not happen.
At this point I am stuck. And I would tell you what I have been trying so far, but the last couple hours were just poking in the dark pretty much. Therefore the least I can do is write down the steps the code takes till the end:
Important variables etc:
Computer is represented by "O", person by "X"
Array gameData: Starts as [0,1,2,...,8] and replaces the numbers with "X" or "O". It tries to prevent that the tictactoe fields can be selected more than once.
Object player with .person-Array and .computer-Array both start as empty. I use these to check if either of them won the game.
isWinner(PLAYER) iterates through the winning conditions and checks if person or computer match it. The function returns the object ({win:true}) if so.
isTie() checks if there is a tie. It returns the object ({tie:true]), if the conditions isWinner(player.computer) = false, isWinner(player.person) = false and emptySpaces(gameData).length = 0 are met.
the function bestMove() searches for the bestMove of computer. Here's where minimax gets executed.
Code Logic overall:
the code starts at line 140 with function vsComputerGame()
next step is function personMove() in line 301
the player's choice "X" gets stored in the gameData Array. EG gameData = [0,"X",2,...,8]. And the position of "X" (in the exp 1`) gets pushed into player.person.
next it checks, if the person won the game or the game is a tie.
next the function bestMove() gets executed. It chooses a tictactoe-field for the computer.
next player.person and player.computer get updated. Without this step, minimax keeps pushing numbers in those arrays.
Code logic bestMove() and minimax():
bestMove() starts at line 190
the initial player.person and player.computer are saved, to restore them, right after the minimax() function returns a value. Same problem as above: Otherwise, isWinner() returns true on the second click of the player.
for loop gets executed. It selects the first available spot in gameData and replaces it with an "O". player.computer gets updated with this possible move from the computer.
then minimax gets executed, which basically has the same code for both player.computer and player.person, as described in this for loop.
when minimax() returns a value, it get stored in the variable score.
now the gameData Array, player.person and player.computer are reset, so the next iteration of the for loop does not flood them.
at last the if (score.eval > bestScore) checks for the highest score. If highest, the index of the current iteration gets stored in the move variable and is then used to place the "O" on the visible field and inside gameData.
"use strict"
// this function stores the chosen players (condition: player1, player2, computer). The start-game is in another module
let menupage = (function() {
let playerSelection = document.querySelectorAll(".player-selection");
let modalContainer = document.querySelector(".modal-bg");
let submitName = document.querySelector("#submit");
let btnColorPlayerTwo = document.querySelector("#player-two");
let btnColorComputer = document.querySelector("#computer");
let btnColorplayerOne = document.querySelector("#player-one");
let modalClose = document.querySelector(".modal-close");
let inputField = document.querySelector("#name");
let isplayerOne;
let gameModeData = {
playerOne : "",
playerTwo : "",
computer : false,
}
function closeModal() {
inputField.value = "";
modalContainer.classList.remove("bg-active");
}
function submitPlayer() {
if (isplayerOne === true) {
if (inputField.value === "") {
alert("Please enter your battle-tag");
} else if (inputField.value !== "") {
btnColorplayerOne.style.backgroundColor = "#4CAF50";
gameModeData.playerOne = inputField.value;
inputField.value = "";
modalContainer.classList.remove("bg-active");
}
}
if (isplayerOne === false) {
if (inputField.value === "") {
alert("Please enter your battle-tag");
} else if (inputField.value !== "") {
gameModeData.playerTwo = inputField.value;
btnColorPlayerTwo.style.backgroundColor = "#f44336";
gameModeData.computer = false;
btnColorComputer.style.backgroundColor = "#e7e7e7";
inputField.value = "";
modalContainer.classList.remove("bg-active");
}
}
}
function definePlayer(id, color) {
modalClose.addEventListener("click", closeModal);
if (id === "player-one") {
if (color.backgroundColor === "" || color.backgroundColor === "rgb(231, 231, 231)") {
isplayerOne = true;
modalContainer.classList.add("bg-active");
submitName.addEventListener("click", submitPlayer);
} else if (color.backgroundColor === "rgb(76, 175, 80)") {
color.backgroundColor = "#e7e7e7";
gameModeData.playerOne = "";
}
}
if (id === "player-two") {
if (color.backgroundColor === "" || color.backgroundColor === "rgb(231, 231, 231)") {
isplayerOne = false;
modalContainer.classList.add("bg-active");
submitName.addEventListener("click", submitPlayer);
}
}
}
function defineOponent(target) {
if (target.backgroundColor === "rgb(0, 140, 186)") {
return;
} else if (target.backgroundColor === "rgb(231, 231, 231)" || target.backgroundColor === "") {
target.backgroundColor = "#008CBA";
btnColorPlayerTwo.style.backgroundColor = "#e7e7e7";
gameModeData.playerTwo = "";
gameModeData.computer = true;
}
}
let setupPlayers = function setupPlayers() {
if (this.id === "player-one" || this.id === "player-two") {
definePlayer(this.id, this.style);
} else if (this.id === "computer") {
defineOponent(this.style);
}
}
playerSelection.forEach(button => button.addEventListener("click", setupPlayers))
return gameModeData;
}())
let startRound = (function startRound() {
let startGameBtn = document.querySelector("#start-game");
let startScreen = document.querySelector(".start-screen");
let gameboard = document.querySelector(".gameboard");
let selectionMenu = document.querySelector(".window-container");
let frame = document.querySelector(".frame");
let scoreboardPlayer = document.querySelector(".scoreboard-left");
let scoreboardOponent = document.querySelector(".scoreboard-right");
let scorePlayer = document.querySelector(".scoreboard-player");
let scoreOponent = document.querySelector(".scoreboard-oponent");
function displayScore() {
scorePlayer.innerText = menupage.playerOne;
menupage.computer === false ? scoreOponent.innerText = menupage.playerTwo : scoreOponent.innerText = "Computer";
}
function startGame() {
if (menupage.playerOne === "") {
alert("Please choose your profile.");
} else if (menupage.playerTwo === "" && menupage.computer === false) {
alert("Please choose an opponent.")
} else {
startScreen.style.display = "none";
gameboard.style.display = "grid";
scoreboardPlayer.style.display = "grid";
scoreboardOponent.style.display = "grid";
frame.style.display = "none";
selectionMenu.style.gridTemplateAreas = '"header header header" "scoreboard-left gameboard scoreboard-right" "frame frame frame"';
displayScore();
game();
}
}
startGameBtn.addEventListener("click", startGame);
}())
/* ***************************** GAME VS COMPUTER FUNCTION STARTS HERE ************************* */
let vsComputerGame = (function vsComputerGame() {
let player = {
person : [],
computer : [],
}
let gameData = [0, 1, 2, 3, 4, 5, 6, 7, 8]
let isWinner = function isWinner(PLAYER) {
let check = PLAYER.join();
let condition = {
1 : ["0","1","2"],
2 : ["3","4","5"],
3 : ["6","7","8"],
4 : ["0","4","8"],
5 : ["2","4","6"],
6 : ["0","3","6"],
7 : ["1","4","7"],
9 : ["2","5","8"]
}
for (const property in condition) {
if (condition[property].every(v => check.includes(v)) === true) {
return ({win : true});
}
}
return ({win : false });
};
let isTie = function isTie() {
if (emptySpaces(gameData).length === 0 && isWinner(player.computer).win === false && isWinner(player.person).win === false) {
return ({tie: true});
} else {
return ({tie : false});
}
}
function emptySpaces(gameData) {
let updatedBoard = [];
for (let i = 0; i < gameData.length; i++) {
if (gameData[i] !== "X") {
if (gameData[i] !== "O") {
updatedBoard.push(gameData[i]);
}
}
}
return updatedBoard;
}
function bestMove() {
let bestScore = -Infinity;
let move;
// the object player with the values {player:[], computer:[]} is used in isWinner to check who won,
// storedComputer and storedPlayer is needed, to reset both arrays after they go through minimax,
// without, the two object-arrays get fludded
let storedComputer = player.computer.map(x => x);
let storedPlayer = player.person.map(x => x);
// first round of the for loop sets a field for the computer,
// first execution of minimax jumps to player.person
for (let i = 0; i < 9; i++) {
// gameData is the Array, that stores the players' moves. Example: [0, 1, 2, "X", 4, 5, "O", 7, 8]
if (gameData[i] !== "X") {
if (gameData[i] !== "O") {
gameData[i] = "O";
player.computer.push(i);
let score = minimax(gameData, player.person);
gameData[i] = i;
player.person = storedPlayer;
player.computer = storedComputer;
if (score.eval > bestScore) {
bestScore = score.eval;
move = i;
console.log(bestScore);
}
}
}
}
// after a move is found for the computer, O gets logged in the gameData Array and on the visible gameboard
let positionO = document.getElementsByName(move);
gameData[move] = "O";
positionO[0].innerText = "O";
}
function minimax(gameData, PLAYER) {
// the BASE of minimax.
// ************ console.log shows, that it always returns -10 ***************
if (isWinner(player.person).win === true) { return ({eval:-10});}
if (isWinner(player.computer).win === true) { return ({eval:10});}
if (isTie().tie === true) {return ({eval:0});};
/*
PLAYER.push pushes the index-number into either player.computer or player.person
This is needed to check the isWinner function
After that, these Arrays get stored in storedComputer and storedPlayer
*/
if (PLAYER === player.computer) {
let bestScore = -Infinity;
for (let i = 0; i < 9; i++) {
if (gameData[i] !== "X") {
if (gameData[i] !== "O") {
PLAYER.push(i);
//let storedComputer = player.computer.map(x => x);
//let storedPlayer = player.person.map(x => x);
gameData[i] = "O";
let score = minimax(gameData, player.person);
//player.person, player.computer and gameData are resetted, after minimax returns a value
gameData[i] = i;
//player.person = storedPlayer;
//player.computer = storedComputer;
if (score.eval > bestScore) {
bestScore = score.eval;
}
}
}
}
return bestScore;
} else {
let bestScore = Infinity;
for (let i = 0; i < 9; i++) {
if (gameData[i] !== "X") {
if (gameData[i] !== "O") {
PLAYER.push(i);
//let storedComputer = player.computer.map(x => x);
//let storedPlayer = player.person.map(x => x);
gameData[i] = "X";
let score = minimax(gameData, player.computer);
//player.person = storedPlayer;
//player.computer = storedComputer;
gameData[i] = i;
if (score.eval < bestScore) {
bestScore = score.eval;
}
}
}
}
return bestScore;
}
}
let cells = document.querySelectorAll(".cell");
cells.forEach(cell => cell.addEventListener("click", personMove));
function personMove() {
if (this.innerText === "X" || this.innerText === "O") {
return;
} else {
let playersChoice = this.getAttribute("data-parent");
player.person.push(Number(this.getAttribute("data-parent")));
this.innerText = "X";
gameData[playersChoice] = "X";
if (isWinner(player.person).win === true) {
console.log("Win");
};
isTie();
bestMove();
player.computer = [];
player.person = [];
for (let i = 0; i < 9; i++) {
if (gameData[i] === "X") {
player.person.push(i);
} else if (gameData[i] === "O") {
player.computer.push(i);
}
}
}
}
})
/* ***************************** GAME VS COMPUTER FUNCTION ENDS HERE ************************* */
let vsPersonGame = (function vsPersonGame() {
let i = 1;
let player = [];
let oponent = [];
let buttons = document.querySelectorAll(".cell");
buttons.forEach(button => button.addEventListener("click", selection));
function selection() {
let newLocal = this
storeSelection(newLocal);
checkWinner();
}
function storeSelection(input) {
if (i >= 10 || input.innerText !== "") {
return;
} else if (i % 2 === 0) {
return input.innerText = "O", oponent.push(input.dataset.parent),
i++;
} else if (i % 2 !== 0) {
return input.innerText = "X", player.push(input.dataset.parent),
i++;
}
}
function checkWinner() {
let condition = {
1 : ["0","1","2"],
2 : ["3","4","5"],
3 : ["6","7","8"],
4 : ["0","4","8"],
5 : ["2","4","6"],
6 : ["0","3","6"],
7 : ["1","4","7"],
9 : ["2","5","8"]
}
for (const property in condition) {
let toStringplayer = player.join();
let toStringoponent = oponent.join();
if (condition[property].every(v => toStringplayer.includes(v)) === true) {
return alert(menupage.playerOne + " won");
} else if (condition[property].every(v => toStringoponent.includes(v)) === true) {
return alert(menupage.playerTwo + " won");
} else if (i === 10) {
if (condition[property].every(v => toStringplayer.includes(v)) === true) {
return alert(menupage.playerOne + " won");
} else if (condition[property].every(v => toStringoponent.includes(v)) === true) {
return alert(menupage.playerTwo + " won");
} else {
return alert("You tied");
}
}
}
}
})
let game = (function() {
if (menupage.computer === true) {
vsComputerGame();
} else {
vsPersonGame();
}
});
html, body {
display: grid;
height: 100%;
margin: 0;
padding: 0;
}
.window-container {
display: grid;
height: 100%;
grid-template-rows: 10% 80% 10%;
grid-template-areas:
"header header header"
". start-screen ."
"frame frame frame";
}
.header {
grid-area: header;
margin-top: 50px;
font-size: 30px;
text-align: center;
color: red;
font-weight: bolder;
}
.start-screen {
grid-area: start-screen;
display: flex;
justify-content: center;
align-items: center;
margin-bottom: 30%;
}
.selection-menu {
flex: 1;
display: grid;
grid-template-rows: 40% 20% 40%;
grid-template-areas:
". . player-two"
"player-one vs ."
". . computer"
}
#player-one {
grid-area: player-one;
background-color: #e7e7e7;
}
#player-two {
grid-area: player-two;
background-color: #e7e7e7;
}
#computer {
grid-area: computer;
background-color: #e7e7e7;
}
#start-game {
display: flex;
cursor: pointer;
border: none;
color: white;
background-color: rgb(37, 36, 36);
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}
#vs {
grid-area: vs;
text-align: center;
font-size: 30px;
font-weight: bold;
color: #4CAF50;
}
.player-selection {
cursor: pointer;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}
.gameboard {
grid-area: gameboard;
margin-top: 10%;
display: none;
justify-content: center;
grid-template-rows: 150px 150px 150px;
grid-template-columns: 150px 150px 150px;
grid-template-areas:
"tL tM tR"
"mL mM mR"
"bL bM bR";
}
.frame {
grid-area: frame;
display: flex;
position: fixed;
height: 250px;
bottom: 0px;
left: 0px;
right: 0px;
margin-bottom: 0px;
justify-content: center;
align-items: center;
}
.cell {
display: flex;
justify-content: center;
align-items: center;
font-size: 40px;
cursor: pointer;
}
.unselectable {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
#tL {
grid-area: tL;
border-bottom: 2px solid black;
border-right: 2px solid black;
}
#tM {
grid-area: tM;
border-bottom: 2px solid black;
border-right: 2px solid black;
}
#tR {
grid-area: tR;
border-bottom: 2px solid black;
}
#mL {
grid-area: mL;
border-bottom: 2px solid black;
border-right: 2px solid black;
}
#mM {
grid-area: mM;
border-bottom: 2px solid black;
border-right: 2px solid black;
}
#mR {
grid-area: mR;
border-bottom: 2px solid black;
}
#bL {
grid-area: bL;
border-right: 2px solid black;
}
#bM {
grid-area: bM;
border-right: 2px solid black;
}
#bR {
grid-area: bR;
}
.modal-bg {
position: fixed;
width: 100%;
height: 100vh;
top: 0;
left: 0;
background-color: rgba(0,0,0,0.5);
display: flex;
justify-content: center;
align-items: center;
visibility: hidden;
opacity: 0;
transition: visibility 0s, opacity 0.5s;
}
.bg-active {
visibility: visible;
opacity: 1;
}
.modal {
position: relative;
background-color: white;
border-radius: 5px 5px 5px 5px;
width: 30%;
height: 20%;
display: flex;
justify-content: space-around;
align-items: center;
flex-direction: column;
}
.modal button {
padding: 10px 50px;
background-color: #2980b9;
color: white;
border: none;
cursor: pointer;
}
.modal-close {
position: absolute;
top: 10px;
right: 10px;
font-weight: bold;
cursor: pointer;
}
#modal-headline {
font-size: 20px;
}
#submit {
margin-top: 5px;
}
.scoreboard-left {
display: none;
}
.scoreboard-player {
grid-area: scoreboard-player;
display: flex;
}
.scoreboard-right {
display: none;
}
.scoreboard-oponent {
grid-area: scoreboard-oponent;
display: flex;
}
<!DOCTYPE html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="UTF-8">
<link href="styles.css" rel="stylesheet" type="text/css" />
<script src="script.js" defer></script>
<title>Tic Tac Toe</title>
</head>
<body>
<div class="window-container">
<div class="header">Tic Tac Toe</div>
<div class="start-screen">
<div class="selection-menu">
<button class="player-selection" id="player-one">Player One</button>
<button class="player-selection" id="player-two">Player Two</button>
<div id="vs">vs</div>
<button class="player-selection" id="computer">Computer</button>
</div>
</div>
<div class="gameboard">
<div class="cell unselectable" id="tL" data-parent="0" name="0"></div>
<div class="cell unselectable" id="tM" data-parent="1" name="1"></div>
<div class="cell unselectable" id="tR" data-parent="2" name="2"></div>
<div class="cell unselectable" id="mL" data-parent="3" name="3"></div>
<div class="cell unselectable" id="mM" data-parent="4" name="4"></div>
<div class="cell unselectable" id="mR" data-parent="5" name="5"></div>
<div class="cell unselectable" id="bL" data-parent="6" name="6"></div>
<div class="cell unselectable" id="bM" data-parent="7" name="7"></div>
<div class="cell unselectable" id="bR" data-parent="8" name="8"></div>
</div>
<div class="modal-bg">
<div class="modal">
<h2 id="modal-headline">Choose a Name:</h2>
<input type="text" id="name">
<button id="submit" class="submit">Submit</button>
<span class="modal-close">X</span>
</div>
</div>
<div class="frame">
<button id="start-game">Start Game</button>
</div>
<div class="scoreboard-left">
<div class="display-player">
<div class="scoreboard-player"></div>
<div class="p-win">Wins: </div><div class="player-win">0</div>
<div class="p-loss">Losses: </div><div class="player-loss">0</div>
<div class="p-tie">Ties: </div><div class="player-tie">0</div>
</div>
</div>
<div class="scoreboard-right">
<div class="display-oponent">
<div class="scoreboard-oponent"></div>
<div class="o-win">Wins: </div><div class="oponent-win">0</div>
<div class="o-loss">Losses: </div><div class="oponent-loss">0</div>
<div class="o-tie">Ties: </div><div class="oponent-tie">0</div>
</div>
</div>
</div>
</body>
</html>
I appreciate any feedback and hints to solve the problem.

i have a problem with writing one js and setting it to multiple divs with same id

hi so this is my js and the problem i have is my js works fine with the first div but it has no effect on the other divs, and i cant seem to find whats the problem. i guess i know what the problem is the only issue i have is i dont know how to solve it, i would appreciate it if u could help me
this is my js:
var incrementerHandle = document.querySelector('.incrementer .value');
var incrementValue = document.querySelector('.incrementer .value span');
var downButton = document.querySelector('.incrementer .down');
var upButton = document.querySelector('.incrementer .up');
var peek = document.querySelector('.incrementer .peek'); //Handle Bounds
var neutral = '50%';
var upper = 50;
var lower = 10; //Count Bounds
var count = 0;
var minCount = 0;
var maxCount = 100; //Timer for holding
var timer;
downButton.addEventListener('click', incrementDown);
upButton.addEventListener('click', incrementUp);
function dragEndHandler() {
peek.classList.remove('active');
checkPosition();
clearInterval(timer); //Return to neutral
incrementerHandle.style.left = neutral;
}
function timerTick() {
peek.classList.add('active');
checkPosition();
}
function checkPosition() {
if (dragger.position.x >= upper) {
incrementUp();
} else if (dragger.position.x <= lower) {
incrementDown();
}
}
function incrementUp() {
count++;
if (count > maxCount) {
count = maxCount;
}
updateValue();
}
function incrementDown() {
count--;
if (count < minCount) {
count = minCount;
}
updateValue();
}
function updateValue() {
incrementValue.innerHTML = count;
checkDisplay();
}
function checkDisplay() {
if (count <= minCount) {
downButton.classList.add('disabled');
} else if (count >= maxCount) {
upButton.classList.add('disabled');
} else {
downButton.classList.remove('disabled');
upButton.classList.remove('disabled');
}
}
<div class="slider">
<div class="incrementer">
<button class="mdc-button mdc-button--raised up">
<span class="mdc-button__ripple">+</span>
</button>
<button class="value">
<span>0</span>
</button>
<button class="mdc-button mdc-button--raised down">
<span class="mdc-button__ripple">-</span>
</button>
</div>
</div>
Based on your explanation on the comment line, you have multiple divs with class slider with similar implementation as the one you posted. In this case you would have to use querySelectorAll() which returns a node list, rather than using querSelector() which returns a single element. I have made a few more adjustments accordingly.
var downButton = document.querySelectorAll('.incrementer .down');
var upButton = document.querySelectorAll('.incrementer .up');
var peek = document.querySelector('.incrementer .peek'); //Handle Bounds
var neutral = '50%';
var upper = 50;
var lower = 10; //Count Bounds
var minCount = 0;
var maxCount = 100; //Timer for holding
var timer;
downButton.forEach( down => down.addEventListener('click', incrementDown));
upButton.forEach( up => up.addEventListener('click', incrementUp));
function dragEndHandler() {
peek.classList.remove('active');
checkPosition();
clearInterval(timer); //Return to neutral
incrementerHandle.style.left = neutral;
}
function timerTick() {
peek.classList.add('active');
checkPosition();
}
function checkPosition() {
if (dragger.position.x >= upper) {
incrementUp();
} else if (dragger.position.x <= lower) {
incrementDown();
}
}
function incrementUp(e) {
let element = e.target;
let count = 0;
if( element.classList.contains('mdc-button') ){
count = Number( element.nextElementSibling.firstElementChild.innerHTML ) + 1;
if (count > maxCount) {
count = maxCount;
}
element.nextElementSibling.firstElementChild.innerHTML = count;
checkDisplay(count, element);
}
else {
count = Number( element.parentElement.nextElementSibling.firstElementChild.innerHTML ) + 1;
if (count > maxCount) {
count = maxCount;
}
element.parentElement.nextElementSibling.firstElementChild.innerHTML = count;
checkDisplay(count, element.parentElement);
}
}
function incrementDown(e) {
let element = e.target;
let count = 0;
if( element.classList.contains('mdc-button') ){
count = Number( element.previousElementSibling.firstElementChild.innerHTML ) - 1;
if (count < minCount) {
count = minCount;
}
element.previousElementSibling.firstElementChild.innerHTML = count;
checkDisplay(count, element);
}
else {
count = Number( element.parentElement.previousElementSibling.firstElementChild.innerHTML ) - 1;
if (count < minCount) {
count = minCount;
}
element.parentElement.previousElementSibling.firstElementChild.innerHTML = count;
checkDisplay(count, element.parentElement);
}
}
function checkDisplay(count, element) {
if (count <= minCount) {
element.classList.add('disabled');
} else if (count >= maxCount) {
element.classList.add('disabled');
} else {
element.classList.remove('disabled');
element.classList.remove('disabled');
}
}
#con{
border: 1px solid black;
padding: 10px;
width: 65%;
margin: 0 auto;
display: flex;
flex-direction: column;
justify-content: space-around;
text-align: center;
}
#con1{
border: 1px solid black;
flex-wrap: wrap;
display: flex;
flex-direction: row;
justify-content: space-around;
padding: 5px;
}
button{
background-color: #4CAF50; /* Green */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}
select{
margin-top: 20px;
}
.redbu{
background-color: red;
}
.bluebu{
background-color: royalblue;
}
.greenbu{
background-color: #4CAF50;
}
.yellowbu{
background-color: yellow;
}
<div class="slider">
<div class="incrementer">
<button class="mdc-button mdc-button--raised up">
<span class="mdc-button__ripple">+</span>
</button>
<button class="value">
<span>0</span>
</button>
<button class="mdc-button mdc-button--raised down">
<span class="mdc-button__ripple">-</span>
</button>
</div>
</div>
<div class="slider">
<div class="incrementer">
<button class="mdc-button mdc-button--raised up">
<span class="mdc-button__ripple">+</span>
</button>
<button class="value">
<span>0</span>
</button>
<button class="mdc-button mdc-button--raised down">
<span class="mdc-button__ripple">-</span>
</button>
</div>
</div>
<div class="slider">
<div class="incrementer">
<button class="mdc-button mdc-button--raised up">
<span class="mdc-button__ripple">+</span>
</button>
<button class="value">
<span>0</span>
</button>
<button class="mdc-button mdc-button--raised down">
<span class="mdc-button__ripple">-</span>
</button>
</div>
</div>

Add/remove box in html using angularJS

I want to create/use an add-remove box like this in HTML using angularJS where you have a list of some objects on the left and you select the objects to put them on under the headings listed on the right. Any idea what do we call such tables/lists and can I create/find them?
I don't know what is the accurate title to call it :)
but I tried to implement a sample of 'add/remove box' to achieve the concept you want with AngularJS!
the main part consists of three sections:
left section which is going to be added
middle section which contains the buttons
right section which is going to be removed
The code below applies the above section which aforesaid:
<div class="box leftBox">
<div>
<div id="{{left.name}}" ng-click="clicked($event, 0)" data-ng-repeat="left in lefts">{{left.name}}</div>
</div>
</div>
<div class="box button_holder">
<button ng-click="add()" class="button button-blue">ADD ></button>
<button ng-click="remove()" class="button button-red">< REMOVE</button>
<button ng-click="addAll()" class="button button-blue button-dark">ADD ALL >></button>
<button ng-click="removeAll()" class="button button-red button-dark"><< REMOVE ALL</button>
<button ng-click="deleteChoice()" class="button delete">X</button>
</div>
<div class="box rightBox">
<div>
<div ng-click="clicked($event, 1)" data-ng-repeat="right in rights">{{right.name}}</div>
</div>
</div>
by using angularjs directives including data-ng-repeat you can control the procedure of adding or removing
here is the implemented overview.
here is the completed code on the "codepen".
you can also check my github.
try to run the snippet in a fullscreen window!
/**
* Created by ALIREZA on 8/30/2017.
*/
var app = angular.module('Add_Remove_Box', []);
app.controller('Ctrl', function($scope) {
var i;
var isRepeated = false;
var actionLicense = true;
var prevElement = null;
var currentElement = null;
var positionSide = null;
$scope.choices = ["left", "right"];
$scope.lefts = [{
id: 'left1'
}, {
id: 'left2'
}, {
id: 'left3'
}, {
id: 'left4'
}];
for (i = 0; i < $scope.lefts.length; i++) {
$scope.lefts[i].name = "left" + (i + 1).toString();
}
$scope.rights = [{
id: 'right1'
}, {
id: 'right2'
}];
for (i = 0; i < $scope.rights.length; i++) {
$scope.rights[i].name = "right" + (i + 1).toString();
}
$scope.insert = function($event) {
var side = $scope.selectedSide;
if (side == null || side == "left") {
var leftItemNo = $scope.lefts.length + 1;
$scope.lefts.push({
'id': 'left' + leftItemNo
});
$scope.lefts[leftItemNo - 1].name = $scope.choice.name;
} else {
var rightItemNo = $scope.rights.length + 1;
$scope.rights.push({
'id': 'right' + rightItemNo
});
$scope.rights[rightItemNo - 1].name = $scope.choice.name;
}
};
$scope.deleteChoice = function() {
if (positionSide === 0) {
var ItemNo = -1;
$scope.lefts.forEach(function(i, j) {
if (i.name === currentElement.textContent) {
ItemNo = j;
return;
}
});
$scope.lefts.splice(ItemNo, 1);
}
};
$scope.add = function() {
if (actionLicense && positionSide === 0) {
actionLicense = false;
var leftItemNo = -1;
$scope.lefts.forEach(function(i, j) {
if (i.name === currentElement.textContent) {
leftItemNo = j;
return;
}
});
$scope.lefts.splice(leftItemNo, 1);
var rightItemNo = $scope.rights.length + 1;
$scope.rights.push({
'id': 'right' + rightItemNo
});
$scope.rights[rightItemNo - 1].name = currentElement.textContent;
}
};
$scope.remove = function() {
if (actionLicense && positionSide === 1) {
actionLicense = false;
var rightItemNo = -1;
$scope.rights.forEach(function(i, j) {
if (i.name === currentElement.textContent) {
rightItemNo = j;
return;
}
});
$scope.rights.splice(rightItemNo, 1);
var leftItemNo = $scope.lefts.length + 1;
$scope.lefts.push({
'id': 'left' + leftItemNo
});
$scope.lefts[leftItemNo - 1].name = currentElement.textContent;
}
};
$scope.addAll = function() {
$scope.lefts.forEach(function(i) {
var rightItemNo = $scope.rights.length + 1;
$scope.rights.push({
'id': 'right' + rightItemNo
});
$scope.rights[rightItemNo - 1].name = i.name;
});
$scope.lefts.splice(0, $scope.lefts.length);
};
$scope.removeAll = function() {
$scope.rights.forEach(function(i) {
var leftItemNo = $scope.lefts.length + 1;
$scope.lefts.push({
'id': 'left' + leftItemNo
});
$scope.lefts[leftItemNo - 1].name = i.name;
});
$scope.rights.splice(0, $scope.rights.length);
};
$scope.clicked = function($event, pos) {
actionLicense = true;
positionSide = pos;
currentElement = $event.currentTarget;
var deleteButton = document.getElementsByClassName("delete")[0];
if (pos === 1) {
if (deleteButton.className.indexOf("button-deactive") === -1) {
deleteButton.className += " button-deactive";
}
} else {
deleteButton.className = deleteButton.className.replace(" button-deactive", "");
}
if (prevElement === null) {
prevElement = currentElement;
} else {
if (prevElement === currentElement) {
isRepeated = !isRepeated;
} else {
if (isRepeated) {
isRepeated = false;
}
}
}
if (prevElement.className.indexOf("active") !== -1) {
prevElement.className = prevElement.className.replace(" active", "");
}
if (!isRepeated && currentElement.className.indexOf("active") === -1) {
currentElement.className += " active";
}
prevElement = currentElement;
};
});
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
padding: 0;
}
.container {
display: inline-block;
width: 100%;
padding: 10px;
height: 100vh;
border: #E64A19 inset .7vh;
background: #616161;
/* fallback for old browsers */
background: -webkit-linear-gradient(to left, #9bc5c3, #616161);
/* Chrome 10-25, Safari 5.1-6 */
background: linear-gradient(to left, #9bc5c3, #616161);
/* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
}
.addItems {
height: 10vh;
margin-bottom: 5vh;
}
.box {
float: left;
display: inline-block;
margin: 0;
padding: 10px;
height: 80vh;
border: #cfcfcf outset 2px;
color: #eee;
font-size: medium;
}
.box>div {
border: #FFF59D ridge 2px;
border-bottom: none;
border-radius: 5px;
}
.box>div>div {
padding: 7px;
border-bottom: #FFF59D ridge 2px;
}
.box>div>div:hover {
background-color: rgba(100, 150, 220, .5);
transition: background-color .4s ease;
}
.box>button {
display: inline-block;
width: 70%;
margin: 5% 15%;
}
.button {
padding: 10px 24px;
border-radius: 3px;
border: none;
box-shadow: 2px 5px 10px rgba(22, 22, 22, .1);
}
.button:hover {
transition: all 60ms ease;
opacity: .95;
box-shadow: #444 0 3px 3px 0;
}
.button-blue {
color: #FFFFFF;
background: #416dea;
}
.button-red {
color: #FFFFFF;
background: #F32C52;
}
.button-dark {
filter: brightness(85%) contrast(110%);
}
.leftBox {
width: 40%;
}
.button_holder {
width: 20%;
}
.rightBox {
width: 40%;
}
input[type="text"],
select {
padding: 5px;
}
.active {
transition: all .1s ease;
background-color: #888;
color: #000;
;
border: dotted 1px black;
box-shadow: 0 2px 2px 0 rgba(97, 97, 97, .5);
margin-bottom: 1px;
}
.button-deactive {
opacity: .5;
box-shadow: none;
}
.button-deactive:hover {
opacity: .5;
box-shadow: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AddRemoveBox</title>
<link rel="stylesheet" href="index.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<!--include angularJs-->
<script src="index.js"></script>
</head>
<body>
<div class="container" ng-app="Add_Remove_Box" ng-controller="Ctrl">
<fieldset class="addItems">
<legend>Insert Items</legend>
<select ng-model="selectedSide">
<option ng-repeat="choice in choices">{{choice}}</option>
</select>
<input type="text" ng-model="choice.name" name="" placeholder="Enter The Item Name">
<button class="button insert" value="insert" ng-click="insert($event)">Insert</button>
</fieldset>
<div class="box leftBox">
<div>
<div id="{{left.name}}" ng-click="clicked($event, 0)" data-ng-repeat="left in lefts">{{left.name}}</div>
</div>
</div>
<div class="box button_holder">
<button ng-click="add()" class="button button-blue">ADD ></button>
<button ng-click="remove()" class="button button-red">< REMOVE</button>
<button ng-click="addAll()" class="button button-blue button-dark">ADD ALL >></button>
<button ng-click="removeAll()" class="button button-red button-dark"><< REMOVE ALL</button>
<button ng-click="deleteChoice()" class="button delete">X</button>
</div>
<div class="box rightBox">
<div>
<div ng-click="clicked($event, 1)" data-ng-repeat="right in rights">{{right.name}}</div>
</div>
</div>
</div>
</body>
</html>

Move div to certain table cell according to random number [duplicate]

This question already has answers here:
How to move an element into another element
(16 answers)
Closed 7 years ago.
I am new at JavaScript. I am trying to make Snakes and Ladders game with native JavaScript code as much as possible. My problem is that I can not move players from their initial position according to the random number generated when pressing on dice image. Can anyone help me on how to move players?
var gameBoard = {
createBoard: function(dimension, mount, intialPosition) {
var mount = document.querySelector(mount);
if (!dimension || isNaN(dimension) || !parseInt(dimension, 10)) {
return false;
} else {
dimension = typeof dimension === 'string' ? parseInt(dimension, 10) : dimension;
var table = document.createElement('table'),
row = document.createElement('tr'),
cell = document.createElement('td'),
rowClone,
cellClone;
var output;
for (var r = 0; r < dimension; r++) {
rowClone = row.cloneNode(true);
table.appendChild(rowClone);
for (var c = 0; c < dimension; c++) {
cellClone = cell.cloneNode(true);
rowClone.appendChild(cellClone);
}
}
mount.appendChild(table);
output = gameBoard.enumerateBoard(table, intialPosition);
}
return output;
},
enumerateBoard: function(board) {
var rows = board.getElementsByTagName('tr'),
text = document.createTextNode(''),
rowCounter = 1,
size = rows.length,
cells,
cellsLength,
cellNumber,
odd = false,
control = 0;
for (var r = size - 1; r >= 0; r--) {
cells = rows[r].getElementsByTagName('td');
cellsLength = cells.length;
rows[r].className = r % 2 == 0 ? 'even' : 'odd';
odd = ++control % 2 == 0 ? true : false;
size = rows.length;
for (var i = 0; i < cellsLength; i++) {
if (odd == true) {
cellNumber = --size + rowCounter - i;
} else {
cellNumber = rowCounter;
}
cells[i].className = i % 2 == 0 ? 'even' : 'odd';
cells[i].id = cellNumber;
cells[i].appendChild(text.cloneNode());
cells[i].firstChild.nodeValue = cellNumber;
rowCounter++;
}
}
var lastRow = rows[0].getElementsByTagName('td');
lastRow[0].id = 'lastCell';
var firstRow = rows[9].getElementsByTagName('td');
firstRow[0].id = 'firstCell';
intialPosition();
return gameBoard;
}
};
window.onload = (function(e) {
gameBoard.createBoard(10, "#grid", intialPosition);
});
var face1 = new Image()
face1.src = "d1.gif"
var face2 = new Image()
face2.src = "d2.gif"
var face3 = new Image()
face3.src = "d3.gif"
var face4 = new Image()
face4.src = "d4.gif"
var face5 = new Image()
face5.src = "d5.gif"
var face6 = new Image()
face6.src = "d6.gif"
function rollDice() {
var randomdice = Math.floor(Math.random() * 6) + 1;
document.images["mydice"].src = eval("face" + randomdice + ".src")
if (randomdice == 6) {
alert('Congratulations! You got 6! Roll the dice again');
}
return randomdice;
}
function intialPosition() {
$("#firstCell").append($("#player1"));
$("#firstCell").append($("#player2"));
}
/*body {
background-image: url('snakesandladder2.png');
background-repeat: no-repeat;
background-size: 100%;
background-color: #4f96cb;
}*/
#game {
width: 80%;
margin-left: auto;
margin-right: auto;
display: table;
}
#gameBoardSection {
border: 3px inset #0FF;
border-radius: 10px;
width: 65%;
display: table-cell;
}
table {
width: 100%;
}
td {
border-radius: 10px;
width: 60px;
height: 60px;
line-height: normal;
vertical-align: bottom;
text-align: left;
border: 0px solid #FFFFFF;
position: relative;
}
table tr:nth-child(odd) td:nth-child(even),
table tr:nth-child(even) td:nth-child(odd) {
background-color: PowderBlue;
}
table tr:nth-child(even) td:nth-child(even),
table tr:nth-child(odd) td:nth-child(odd) {
background-color: SkyBlue;
}
#lastCell {
background-image: url('rotstar2_e0.gif');
background-repeat: no-repeat;
background-size: 100%;
}
#ladder {
position: absolute;
top: 300px;
left: 470px;
-webkit-transform: rotate(30deg);
z-index: 1;
opacity: 0.7;
}
#bigSnake {
position: absolute;
top: 20px;
left: 200px;
opacity: 0.7;
z-index: 1;
}
#diceAndPlayerSection {
background-color: lightpink;
border: 1px;
border-style: solid;
display: table-cell;
border-radius: 10px;
border: 3px inset #0FF;
width: 35%;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link href="StyleSheet1.css" rel="stylesheet" />
<script src="jquery-2.1.4.min.js"></script>
</head>
<body>
<div id="game">
<div id="gameBoardSection">
<div id="grid"></div>
<div id="ladder">
<img src="oie_eRDOY2iqd5oQ.gif" />
</div>
<div id="bigSnake">
<img src="oie_485727sRN4KKBG.png" />
</div>
<div id="player1" style="position:absolute; top:10px; left:10px;">
<img src="humanPiece.png" />
</div>
<div id="player2" style="position:absolute; top:15px; left:5px;">
<img src="computerPiece.png" />
</div>
</div>
<div id="diceAndPlayerSection">
<div id="reset">
<button type="button" name="reset">New Game</button>
</div>
<div>
<button type="button" name="reset">Reset</button>
</div>
<div>
<button type="button" name="addPlayer">Add Player</button>
</div>
<div id="diceSection">
<img src="d1.gif" name="mydice" onclick="rollDice()" style="background-color: white;">
<!--<h2 id="status" style="clear:left;"></h2>-->
</div>
</div>
</div>
<script src="JavaScript1.js"></script>
</body>
</html>
I fell miserable about not being able to finish the game. I really need help. Thanks in advance.
Well, first of all this question has been already asked and answered on SO and table cells are just the same as usual elements :)
Since you're using jQuery anyway, you can use .detach()
var element = $('td:eq(0) span').detach();
$('td:eq(1)').append(element);
Here's a jsfiddle.
Or, as proposed in this answer, you can use a native js solution.

Categories

Resources