Related
Say a user has a HTML file, and they are using a touchscreen device, say a phone.
I have this set of code right here:
W.onmousedown = function () {
gameOver();
}
Basically what it does is detect if the div named W was clicked and if so, end the game.
I want to do this same thing but instead, it's detecting if the user touched the DIV on their screen. How can I do this?
Edit:
Using click for me doesn't work, it doesn't end the game. This is my code:
var gameIsPlaying = true;
function game() {
gameIsPlaying = true;
const RandomLetterGUI = document.getElementById("RandomLetters")
const TimerGUI = document.getElementById("Timer")
const LivesGUI = document.getElementById("Lives")
const ScoreGUI = document.getElementById("Score")
const W = document.getElementById("W")
const A = document.getElementById("A")
const S = document.getElementById("S")
const D = document.getElementById("D")
W.style.backgroundColor = "white";
W.innerHTML = 'W'
A.style.backgroundColor = "white";
A.innerHTML = 'A'
S.style.backgroundColor = "white";
S.innerHTML = 'S'
D.style.backgroundColor = "white";
D.innerHTML = 'D'
const letters = [
"W",
"A",
"S",
"D"
]
var seconds = 60;
var lives = 3;
var score = 0;
var timerId = setInterval(countdown, 1000);
function countdown() {
if (seconds == -1) {
gameOver()
} else {
if (seconds > 9) {
TimerGUI.innerHTML = ':' + seconds;
} else {
TimerGUI.innerHTML = ':0' + seconds;
}
seconds--;
}
}
countdown()
const updateLives = setInterval(displayLives, 0)
const ScoreUpdate = setInterval(updateScore, 0)
function gameOver() {
gameIsPlaying = false
clearTimeout(timerId)
clearTimeout(updateLives)
clearTimeout(ScoreUpdate)
W.style.backgroundColor = "red";
W.innerHTML = ''
A.style.backgroundColor = "red";
A.innerHTML = ''
S.style.backgroundColor = "red";
S.innerHTML = ''
D.style.backgroundColor = "red";
D.innerHTML = ''
RandomLetterGUI.innerHTML = ''
TimerGUI.innerHTML = ''
LivesGUI.innerHTML = ''
ScoreGUI.innerHTML = ''
}
function updateScore() {
ScoreGUI.innerHTML = "Score: " + score
}
function displayLives() {
LivesGUI.innerHTML = "Remaining Lives: " + lives
if (lives == 0) {
gameOver()
}
}
function letter() {
var item = letters[Math.floor(Math.random() * letters.length)];
RandomLetterGUI.innerHTML = "Next Letter: " + item
var pickedLetterTime = Math.floor(Date.now() / 1000)
document.onkeypress = function(e) {
if (gameIsPlaying) {
var key = e.key
if (key.toUpperCase() != item) {
lives -= 1;
if (score >= 0) {
score -= 50;
}
} else {
var pressedKeyTime = Math.floor(Date.now() / 1000)
var seconds = pressedKeyTime - pickedLetterTime
if (seconds > 0 && seconds < 1.5) {
score += 500
}
if (seconds >= 1.5 && seconds < 3) {
score += 350
}
if (seconds >= 3 && seconds < 5) {
score += 150
}
}
}
};
document.onkeydown = function(e) {
var key = e.key
if (key == "w") {
W.style.backgroundColor = "lime";
W.innerHTML = ''
}
if (key == "a") {
A.style.backgroundColor = "lime";
A.innerHTML = ''
}
if (key == "s") {
S.style.backgroundColor = "lime";
S.innerHTML = ''
}
if (key == "d") {
D.style.backgroundColor = "lime";
D.innerHTML = ''
}
}
document.onkeyup = function(e) {
if (e.key == "w") {
W.style.backgroundColor = "white";
W.innerHTML = 'W'
}
if (e.key == "a") {
A.style.backgroundColor = "white";
A.innerHTML = 'A'
}
if (e.key == "s") {
S.style.backgroundColor = "white";
S.innerHTML = 'S'
}
if (e.key == "d") {
D.style.backgroundColor = "white";
D.innerHTML = 'D'
}
}
// touchscreen compatibility
W.onclick = function() {
gameOver();
}
}
letter()
}
game()
function resetGame() {
if (gameIsPlaying == false) {
document.onkeypress = function(e) {
var key = e.key
if (key == "Enter") {
game()
}
}
}
}
setInterval(resetGame, 0)
body {
background-color: black;
}
p {
font-family: Verdana;
color: white;
font-size: 20px;
}
.RandomLetters {
float: left;
}
.Timer {
float: right;
}
.Lives {
position: absolute;
left: auto;
}
.Score {
position: absolute;
right: 0;
}
.center {
display: flex;
justify-content: center;
align-items: center;
position: absolute;
top: 0;
bottom: 100px;
left: 0;
right: 0;
margin: auto;
}
.center2 {
display: flex;
justify-content: center;
align-items: center;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
.W,
.A,
.S,
.D {
height: 50px;
width: 50px;
font-family: Verdana;
text-align: center;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Play WASD online</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<noscript>turn on javascript to play this game or noob :P</noscript>
<p id="RandomLetters" class="RandomLetters">
</p>
<p id="Timer" class="Timer">
</p>
<br>
<p id="Lives" class="Lives">
</p>
<p id="Score" class="Score">
</p>
<div class="center">
<div id="W" class="W">
</div>
</div>
<div class="center2">
<div id="A" class="A">
</div>
<div id="S" class="S">
</div>
<div id="D" class="D">
</div>
</div>
<script src="script.js"></script>
</body>
</html>
It doesn't work, because you obscured your W container with another one and it's not clickable
I changed the order of containers so the W one is now at the front layer and it works
var gameIsPlaying = true;
function game() {
gameIsPlaying = true;
const RandomLetterGUI = document.getElementById("RandomLetters")
const TimerGUI = document.getElementById("Timer")
const LivesGUI = document.getElementById("Lives")
const ScoreGUI = document.getElementById("Score")
const W = document.getElementById("W")
const A = document.getElementById("A")
const S = document.getElementById("S")
const D = document.getElementById("D")
W.style.backgroundColor = "white";
W.innerHTML = 'W'
A.style.backgroundColor = "white";
A.innerHTML = 'A'
S.style.backgroundColor = "white";
S.innerHTML = 'S'
D.style.backgroundColor = "white";
D.innerHTML = 'D'
const letters = [
"W",
"A",
"S",
"D"
]
var seconds = 60;
var lives = 3;
var score = 0;
var timerId = setInterval(countdown, 1000);
function countdown() {
if (seconds == -1) {
gameOver()
} else {
if (seconds > 9) {
TimerGUI.innerHTML = ':' + seconds;
} else {
TimerGUI.innerHTML = ':0' + seconds;
}
seconds--;
}
}
countdown()
const updateLives = setInterval(displayLives, 0)
const ScoreUpdate = setInterval(updateScore, 0)
function gameOver() {
gameIsPlaying = false
clearTimeout(timerId)
clearTimeout(updateLives)
clearTimeout(ScoreUpdate)
W.style.backgroundColor = "red";
W.innerHTML = ''
A.style.backgroundColor = "red";
A.innerHTML = ''
S.style.backgroundColor = "red";
S.innerHTML = ''
D.style.backgroundColor = "red";
D.innerHTML = ''
RandomLetterGUI.innerHTML = ''
TimerGUI.innerHTML = ''
LivesGUI.innerHTML = ''
ScoreGUI.innerHTML = ''
}
function updateScore() {
ScoreGUI.innerHTML = "Score: " + score
}
function displayLives() {
LivesGUI.innerHTML = "Remaining Lives: " + lives
if (lives == 0) {
gameOver()
}
}
function letter() {
var item = letters[Math.floor(Math.random() * letters.length)];
RandomLetterGUI.innerHTML = "Next Letter: " + item
var pickedLetterTime = Math.floor(Date.now() / 1000)
document.onkeypress = function(e) {
if (gameIsPlaying) {
var key = e.key
if (key.toUpperCase() != item) {
lives -= 1;
if (score >= 0) {
score -= 50;
}
} else {
var pressedKeyTime = Math.floor(Date.now() / 1000)
var seconds = pressedKeyTime - pickedLetterTime
if (seconds > 0 && seconds < 1.5) {
score += 500
}
if (seconds >= 1.5 && seconds < 3) {
score += 350
}
if (seconds >= 3 && seconds < 5) {
score += 150
}
}
}
};
document.onkeydown = function(e) {
var key = e.key
if (key == "w") {
W.style.backgroundColor = "lime";
W.innerHTML = ''
}
if (key == "a") {
A.style.backgroundColor = "lime";
A.innerHTML = ''
}
if (key == "s") {
S.style.backgroundColor = "lime";
S.innerHTML = ''
}
if (key == "d") {
D.style.backgroundColor = "lime";
D.innerHTML = ''
}
}
document.onkeyup = function(e) {
if (e.key == "w") {
W.style.backgroundColor = "white";
W.innerHTML = 'W'
}
if (e.key == "a") {
A.style.backgroundColor = "white";
A.innerHTML = 'A'
}
if (e.key == "s") {
S.style.backgroundColor = "white";
S.innerHTML = 'S'
}
if (e.key == "d") {
D.style.backgroundColor = "white";
D.innerHTML = 'D'
}
}
// touchscreen compatibility
W.onclick = function() {
gameOver();
}
}
letter()
}
game()
function resetGame() {
if (gameIsPlaying == false) {
document.onkeypress = function(e) {
var key = e.key
if (key == "Enter") {
game()
}
}
}
}
setInterval(resetGame, 0)
body {
background-color: black;
}
p {
font-family: Verdana;
color: white;
font-size: 20px;
}
.RandomLetters {
float: left;
}
.Timer {
float: right;
}
.Lives {
position: absolute;
left: auto;
}
.Score {
position: absolute;
right: 0;
}
.center {
display: flex;
justify-content: center;
align-items: center;
position: absolute;
top: 0;
bottom: 100px;
left: 0;
right: 0;
margin: auto;
}
.center2 {
display: flex;
justify-content: center;
align-items: center;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
.W,
.A,
.S,
.D {
height: 50px;
width: 50px;
font-family: Verdana;
text-align: center;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Play WASD online</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<noscript>turn on javascript to play this game or noob :P</noscript>
<p id="RandomLetters" class="RandomLetters">
</p>
<p id="Timer" class="Timer">
</p>
<br>
<p id="Lives" class="Lives">
</p>
<p id="Score" class="Score">
</p>
<div class="center2">
<div id="A" class="A">
</div>
<div id="S" class="S">
</div>
<div id="D" class="D">
</div>
</div>
<div class="center">
<div id="W" class="W">
</div>
</div>
<script src="script.js"></script>
</body>
</html>
var element= document.getElementById("IDName");
element.onclick = function () {
gameOver();
}
you can use click or Pointer Events
You can use the touchstart event for this, see this mdn article
W.ontouchstart = function () {
gameOver();
}
I'm a self taught programmer and I got my hands on a TicTacToe project, but I got stucked at the following part.
I did a relatively working TicTacToe(inspired from youtube) then I wanted to do a responsive TicTacToe matrix that changes it's numbers from(0-9) in X's and O's in the console depending of the inputs of the first game. But now I'm stuck at trying to find a way to check the winners of the matrix oh and I'm trying to start the "checking" from the last X or O
Hopefully seeing the code is much more easier to understand.
I'd really really appreciate some help!
const statusDiv = document.querySelector('.status');
const resetDiv = document.querySelector('.reset');
const cellDivs = document.querySelectorAll('.game-cell');
// game constants
const xSymbol = '×';
const oSymbol = '○';
// game variables
let gameIsLive = true;
let xIsNext = true;
var currentPlayer = 0;
//Random generated
function getInputValue() {
document.getElementById("formInput").style.display = "none";
document.getElementById("container").style.display = "inline";
let player1Input = document.getElementById("player1Input").value;
let player2Input = document.getElementById("player2Input").value;
currentPlayer = 1;
var random = Math.random() * 100;
if (random <= 60) {
currentPlayer = 1;
statusDiv.innerHTML = player1Input + " turn";
statusDiv.style.color = "blue";
}
else {
currentPlayer = 2;
statusDiv.innerHTML = player2Input + " turn";
statusDiv.style.color = "red";
}
}
// statusDiv.style.filter= "green";
//functions
const letterToSymbol = (letter) => letter === 'x' ? xSymbol : oSymbol;
const handleWin = (letter) => {
gameIsLive = false;
if (currentPlayer === 1) {
statusDiv.innerHTML = player1Input.value + " has won!";
statusDiv.style.color = "blue";
} else {
statusDiv.innerHTML = player2Input.value + " has won!";
statusDiv.style.color = "red";
}
};
const checkGameStatus = () => {
const topLeft = cellDivs[0].classList[1];
const topMiddle = cellDivs[1].classList[1];
const topRight = cellDivs[2].classList[1];
const middleLeft = cellDivs[3].classList[1];
const middleMiddle = cellDivs[4].classList[1];
const middleRight = cellDivs[5].classList[1];
const bottomLeft = cellDivs[6].classList[1];
const bottomMiddle = cellDivs[7].classList[1];
const bottomRight = cellDivs[8].classList[1];
// check winner
if (topLeft && topLeft === topMiddle && topLeft === topRight) {
handleWin(topLeft);
cellDivs[0].classList.add('won');
cellDivs[1].classList.add('won');
cellDivs[2].classList.add('won');
} else if (middleLeft && middleLeft === middleMiddle && middleLeft === middleRight) {
handleWin(middleLeft);
cellDivs[3].classList.add('won');
cellDivs[4].classList.add('won');
cellDivs[5].classList.add('won');
} else if (bottomLeft && bottomLeft === bottomMiddle && bottomLeft === bottomRight) {
handleWin(bottomLeft);
cellDivs[6].classList.add('won');
cellDivs[7].classList.add('won');
cellDivs[8].classList.add('won');
} else if (topLeft && topLeft === middleLeft && topLeft === bottomLeft) {
handleWin(topLeft);
cellDivs[0].classList.add('won');
cellDivs[3].classList.add('won');
cellDivs[6].classList.add('won');
} else if (topMiddle && topMiddle === middleMiddle && topMiddle === bottomMiddle) {
handleWin(topMiddle);
cellDivs[1].classList.add('won');
cellDivs[4].classList.add('won');
cellDivs[7].classList.add('won');
} else if (topRight && topRight === middleRight && topRight === bottomRight) {
handleWin(topRight);
cellDivs[2].classList.add('won');
cellDivs[5].classList.add('won');
cellDivs[8].classList.add('won');
} else if (topLeft && topLeft === middleMiddle && topLeft === bottomRight) {
handleWin(topLeft);
cellDivs[0].classList.add('won');
cellDivs[4].classList.add('won');
cellDivs[8].classList.add('won');
} else if (topRight && topRight === middleMiddle && topRight === bottomLeft) {
handleWin(topRight);
cellDivs[2].classList.add('won');
cellDivs[4].classList.add('won');
cellDivs[6].classList.add('won');
} else if (topLeft && topMiddle && topRight && middleLeft && middleMiddle && middleRight && bottomLeft && bottomMiddle && bottomRight) {
gameIsLive = false;
statusDiv.innerHTML = 'Game is tied!';
} else {
xIsNext = !xIsNext;
if (currentPlayer === 2) {
statusDiv.innerHTML = player1Input.value + ` turn`;
statusDiv.style.color = "blue";
currentPlayer = 1;
} else {
currentPlayer = 2;
statusDiv.style.color = "red";
statusDiv.innerHTML = player2Input.value + ` turn`;
}
}
};
// event Handlers
const handleReset = () => {
document.getElementById("formInput").style.display = "inline";
document.getElementById("container").style.display = "none";
xIsNext = true;
statusDiv.innerHTML = `Press Start Game`;
for (const cellDiv of cellDivs) {
cellDiv.classList.remove('x');
cellDiv.classList.remove('o');
cellDiv.classList.remove('won');
document.location.reload()
}
gameIsLive = true;
};
const handleCellClick = (e) => {
const classList = e.target.classList;
if (!gameIsLive || classList[1] === 'x' || classList[1] === 'o') {
return;
}
if (currentPlayer === 1) {
classList.add('playerOneColour');
} else {
classList.add('playerTwoColour');
}
if (xIsNext) {
classList.add("x");
} else {
classList.add('o');
}
checkGameStatus();
};
// event listeners
resetDiv.addEventListener('click', handleReset);
for (const cellDiv of cellDivs) {
cellDiv.addEventListener('click', handleCellClick);
cellDiv.addEventListener('click', handleCellSelection);
}
//Matrix Builder
var counter = 0;
var matrix = [];
for (var i = 0; i < 3; i++) {
matrix[i] = [];
for (var j = 0; j < 3; j++) {
matrix[i][j] = [];
matrix[i][j] = counter;
++counter;
}
}
// 0,1,2,3,4,5,6,7,8
// 0,1,2,0,1,2,0,1,2
var playerCounter = 1;
var currentPlayer = 1;
function handleCellSelection(e) {
playerCounter++;
let htmlElement = e.target;
let cellType = htmlElement.getAttribute("data-cell");
let reuseNTI = numberToIndexes(cellType);
let matrixIndex = indexInMatrix(reuseNTI[0], reuseNTI[1]);
let isWinnerFunction = isPlayerWinner(matrix);
function indexInMatrix(index1, index2) {
if (currentPlayer === 2) {
return matrix[index1].splice([index2], 1, "X")
currentPlayer = 1;
} else {
return matrix[index1].splice([index2], 1, "O");
currentPlayer = 2;
}
}
function isPlayerWinner(matrix, currentPlayer) {
if (playerCounter < 6) {
return;
} else {
var xSign = "X";
var oSign = "O";
let rowX = 0;
let rowO = 0;
//TO DO CHECK COLUMN
for (var i = 0; i < matrix[0].length; i++) {
if (xSign === matrix[i][reuseNTI[0]]) {
rowX++
} else if (oSign === matrix[i][reuseNTI[0]]) {
rowO++
console.log(rowO)
}
// console.log(matrix[i, 0].lastIndexOf("X")) ; //000↓,111↓,222↓
// console.log(matrix[i, 0].lastIndexOf("O"));
}
//TO DO CHECK ROW
for (var i = 0; i < matrix[0].length; i++) {
if (xSign === matrix[reuseNTI[0][i]]) {
} else if (oSign === matrix[reuseNTI[0]][i]) {
}
// console.log(matrix[0, i].lastIndexOf("X")) ; //row is 000->,111->,222->
// console.log(matrix[0, i].lastIndexOf("O"));
}
//TO DO CHECK PRIMARY DIAGONAL
for (var i = 0; i < matrix[0].length; i++) {
if (xSign === matrix[i][i]) {
} else if (oSign === matrix[i][i]) {
}
// matrix[i][i];
// console.log(matrix[i, i].lastIndexOf("X")); //012->,012->,012->
// console.log(matrix[i, i].lastIndexOf("O"));
}
//TO DO CHECK SECONDARY DIAGONAL
for (var i = 0; i < matrix[0].length; i++) {
if (xSign === matrix[i][matrix.length - 1 - i]) {
} else if (oSign === matrix[i][matrix.length - 1 - i]) {
}
// matrix[i][matrix.length - 1 - i];
// console.log(matrix[i, matrix.length - 1 - i].lastIndexOf("X"));
// console.log(matrix[i, [matrix.length - 1 - i]].lastIndexOf("O"));
}
}
}
isPlayerWinner(matrix);
console.log(matrix);
}
function numberToIndexes(number) {
let row = Math.floor(number / 3);
let column = number % 3;
return [row, column];
}
var cellSize = 100;
var cellSpace = 10;
var matrixRows = matrix.length;
var matrixColumns = matrix[0].length;
for (var i = 0; i < matrixRows; i++) {
for (var j = 0; j < matrixColumns; j++) {
var cell = document.createElement("div");
cell.setAttribute("class", "cell");
matrixStage.appendChild(cell);
cell.style.top = i * (cellSize + cellSpace) + "px";
cell.style.left = j * (cellSize + cellSpace) + "px";
}
}
function newMatrixGrid() {
var grid3x3 = document.getElementById("matrixMaker").value;
if (grid3x3 == "3") {
var matrixStage = document.querySelector("#matrixStage").style.display = "block";
} else {
matrixStage = document.querySelector("#matrixStage").style.display = "none";
}
}
#player1{
color: blue;
}
#player2{
color: red;
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
color: #545454;
display: grid;
font-family: sans-serif;
justify-content: center;
}
.container {
background: #ffffff;
margin: 50px;
padding: 50px;
border-radius: 25px;
}
.title {
text-align: center;
}
.title span {
color: #F2EBD3;
}
.status-action {
color:blue;
display: flex;
margin-top: 25px;
font-size: 25px;
justify-content: space-around;
height: 30px;
}
.status span {
color: red;
}
.reset {
color: black;
cursor: pointer;
}
.reset:hover {
color: #10976c;
}
.game-grid {
background: #000000;
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(3, 1fr);
grid-gap: 15px;
margin-top: 50px;
}
.game-cell {
background:white;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
height: 200px;
width: 200px;
}
.playerOneColour{
filter: invert(9%) sepia(100%) saturate(7261%) hue-rotate(247deg) brightness(91%) contrast(146%);
}
.playerTwoColour{
filter: invert(14%) sepia(95%) saturate(6042%) hue-rotate(358deg) brightness(109%) contrast(117%);
}
.x {
color: transparent;
cursor: default;
}
.o {
color: transparent;
cursor: default;
}
.x::after {
background-image: url(../Resources/X.png);
background-size:contain;
background-repeat: no-repeat;
margin-top: 80px;
content: '×';
}
.o::after {
background-image: url(../Resources/O.png);
background-size:contain;
background-repeat: no-repeat;
margin-top: 100px;
content: '○';
}
.won::after {
filter: invert(100%) sepia() saturate(10000%) hue-rotate(0deg);
}
#media only screen and (min-width: 1024px) {
.game-grid {
margin-top: 25px;
grid-gap: 10px;
}
.game-cell {
height: 150px;
width: 150px;
}
.x::after {
font-size: 150px;
}
.o::after {
font-size: 175px;
}
}
#media only screen and (max-width: 540px) {
.container {
margin: 25px;
padding: 25px;
}
.game-cell {
height: 100px;
width: 100px;
}
.x::after {
font-size: 100px;
}
.o::after {
font-size: 125px;
}
}
#matrixStage{
position:relative;
}
.cell
{
position: absolute;
width: 100px;
height: 100px;
border: 1px solid black;
background-color: white;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Play XO</title>
<link rel="StyleSheet" href="Styles/index.css">
</head>
<body>
<form id="formInput">
<h1>Play X O </h1><br>
<label for="player1" id="player1">Player 1:</label><br>
<input type="text" id="player1Input"><br>
<label for="player1" id="player2">Player 2:</label><br>
<input type="text" id="player2Input"><br><br>
<button type="button" onclick="getInputValue();"> Start Game</button>
</form>
<br>
</form>
<div class="container" style="display:none" id="container">
<h1 class="title">Play X O </h1>
<div class="status-action">
<div class="status">Player 1 turn</div>
<div class="reset">Reset</div>
</div>
<div class="game-grid">
<div class="game-cell" data-cell="0"></div>
<div class="game-cell" data-cell="1"></div>
<div class="game-cell" data-cell="2"></div>
<div class="game-cell" data-cell="3"></div>
<div class="game-cell" data-cell="4"></div>
<div class="game-cell" data-cell="5"></div>
<div class="game-cell" data-cell="6"></div>
<div class="game-cell" data-cell="7"></div>
<div class="game-cell" data-cell="8"></div>
</div>
</div>
<select name="matrix-size" id="matrixMaker" onchange="newMatrixGrid()">
<option value="3">3X3</option>
<option value="4">4X4</option>
<option value="5">5X5</option>
</select>
</br></br></br>
<div id="matrixStage"></div>
<script src="Scripts/index.js"></script>
</body>
</html>
I think you can simplify your isPlayerWinner function by ignoring if you are looking for Xs or Os. You must assume the last token used was not the winner in the previous turn or the game would already be finished.
So if you have matrix = [[0,1,2],[3,4,5],[6,7,8]] and the numbers will be progressively replaced by x or o just check if all items in a combination are equal
function isPlayerWinner(){
for(let i=0; i<3; i++){
const row = matrix[i][0] === matrix[i][1] && matrix[i][1] === matrix[i][2];
const column = matrix[0][i] === matrix[1][i] && matrix[1][i] === matrix[2][i];
if(column || row){
return true
}
}
if(matrix[0][0] === matrix[1][1] && matrix[1][1] === matrix[2][2]){
return true;
}
if(matrix[0][2] === matrix[1][1] && matrix[1][1] === matrix[2][0]){
return true;
}
return false
}
When I'm sending this ajax request:
$.ajax({
url: "{{URL::to('admin/repcasetracker/getdiscount')}}",
data: {
serialnumber: serialnumberdata,
},
success: function (data) {
console.log(data);
}
});
Controller:
public function getdiscount(Request $request) {
print_r("hi");
dd($request->all());
}
Then it give me in controller side this type of response:
Sfdump = window.Sfdump || (function (doc) { var refStyle =
doc.createElement('style'), rxEsc = /([.+?^${}()|[]/\])/g, idRx =
/\bsf-dump-\d+-ref[012]\w+\b/, keyHint = 0 <=
navigator.platform.toUpperCase().indexOf('MAC') ? 'Cmd' : 'Ctrl',
addEventListener = function (e, n, cb) { e.addEventListener(n, cb,
false); }; (doc.documentElement.firstElementChild ||
doc.documentElement.children[0]).appendChild(refStyle); if
(!doc.addEventListener) { addEventListener = function (element,
eventName, callback) { element.attachEvent('on' + eventName, function
(e) { e.preventDefault = function () {e.returnValue = false;};
e.target = e.srcElement; callback(e); }); }; } function toggle(a,
recursive) { var s = a.nextSibling || {}, oldClass = s.className,
arrow, newClass; if (/\bsf-dump-compact\b/.test(oldClass)) { arrow =
'▼'; newClass = 'sf-dump-expanded'; } else if
(/\bsf-dump-expanded\b/.test(oldClass)) { arrow = '▶'; newClass
= 'sf-dump-compact'; } else { return false; } a.lastChild.innerHTML = arrow; s.className =
s.className.replace(/\bsf-dump-(compact|expanded)\b/, newClass); if
(recursive) { try { a = s.querySelectorAll('.'+oldClass); for (s = 0;
s < a.length; ++s) { if (-1 == a[s].className.indexOf(newClass)) {
a[s].className = newClass; a[s].previousSibling.lastChild.innerHTML =
arrow; } } } catch (e) { } } return true; }; function collapse(a,
recursive) { var s = a.nextSibling || {}, oldClass = s.className; if
(/\bsf-dump-expanded\b/.test(oldClass)) { toggle(a, recursive); return
true; } return false; }; function expand(a, recursive) { var s =
a.nextSibling || {}, oldClass = s.className; if
(/\bsf-dump-compact\b/.test(oldClass)) { toggle(a, recursive); return
true; } return false; }; function collapseAll(root) { var a =
root.querySelector('a.sf-dump-toggle'); if (a) { collapse(a, true);
expand(a); return true; } return false; } function reveal(node) { var
previous, parents = []; while ((node = node.parentNode || {}) &&
(previous = node.previousSibling) && 'A' === previous.tagName) {
parents.push(previous); } if (0 !== parents.length) {
parents.forEach(function (parent) { expand(parent); }); return true; }
return false; } function highlight(root, activeNode, nodes) {
resetHighlightedNodes(root); Array.from(nodes||[]).forEach(function
(node) { if (!/\bsf-dump-highlight\b/.test(node.className)) {
node.className = node.className + ' sf-dump-highlight'; } }); if
(!/\bsf-dump-highlight-active\b/.test(activeNode.className)) {
activeNode.className = activeNode.className + '
sf-dump-highlight-active'; } } function resetHighlightedNodes(root) {
Array.from(root.querySelectorAll('.sf-dump-str, .sf-dump-key,
.sf-dump-public, .sf-dump-protected,
.sf-dump-private')).forEach(function (strNode) { strNode.className =
strNode.className.replace(/\bsf-dump-highlight\b/, '');
strNode.className =
strNode.className.replace(/\bsf-dump-highlight-active\b/, ''); }); }
return function (root, x) { root = doc.getElementById(root); var
indentRx = new RegExp('^('+(root.getAttribute('data-indent-pad') || '
').replace(rxEsc, '\$1')+')+', 'm'), options =
{"maxDepth":1,"maxStringLength":160,"fileLinkFormat":false}, elt =
root.getElementsByTagName('A'), len = elt.length, i = 0, s, h, t = [];
while (i < len) t.push(elt[i++]); for (i in x) { options[i] = x[i]; }
function a(e, f) { addEventListener(root, e, function (e) { if ('A' ==
e.target.tagName) { f(e.target, e); } else if ('A' ==
e.target.parentNode.tagName) { f(e.target.parentNode, e); } else if
(e.target.nextElementSibling && 'A' ==
e.target.nextElementSibling.tagName) { f(e.target.nextElementSibling,
e, true); } }); }; function isCtrlKey(e) { return e.ctrlKey ||
e.metaKey; } function xpathString(str) { var parts =
str.match(/[^'"]+|['"]/g).map(function (part) { if ("'" == part) {
return '"\'"'; } if ('"' == part) { return "'\"'"; } return "'" + part
+ "'"; }); return "concat(" + parts.join(",") + ", '')"; } addEventListener(root, 'mouseover', function (e) { if ('' !=
refStyle.innerHTML) { refStyle.innerHTML = ''; } }); a('mouseover',
function (a, e, c) { if (c) { e.target.style.cursor = "pointer"; }
else if (a = idRx.exec(a.className)) { try { refStyle.innerHTML =
'pre.sf-dump .'+a[0]+'{background-color: #B729D9; color: #FFF
!important; border-radius: 2px}'; } catch (e) { } } }); a('click',
function (a, e, c) { if (/\bsf-dump-toggle\b/.test(a.className)) {
e.preventDefault(); if (!toggle(a, isCtrlKey(e))) { var r =
doc.getElementById(a.getAttribute('href').substr(1)), s =
r.previousSibling, f = r.parentNode, t = a.parentNode;
t.replaceChild(r, a); f.replaceChild(a, s); t.insertBefore(s, r); f =
f.firstChild.nodeValue.match(indentRx); t =
t.firstChild.nodeValue.match(indentRx); if (f && t && f[0] !== t[0]) {
r.innerHTML = r.innerHTML.replace(new RegExp('^'+f[0].replace(rxEsc,
'\$1'), 'mg'), t[0]); } if (/\bsf-dump-compact\b/.test(r.className))
{ toggle(s, isCtrlKey(e)); } } if (c) { } else if (doc.getSelection) {
try { doc.getSelection().removeAllRanges(); } catch (e) {
doc.getSelection().empty(); } } else { doc.selection.empty(); } } else
if (/\bsf-dump-str-toggle\b/.test(a.className)) { e.preventDefault();
e = a.parentNode.parentNode; e.className =
e.className.replace(/\bsf-dump-str-(expand|collapse)\b/,
a.parentNode.className); } }); elt =
root.getElementsByTagName('SAMP'); len = elt.length; i = 0; while (i <
len) t.push(elt[i++]); len = t.length; for (i = 0; i < len; ++i) { elt
= t[i]; if ('SAMP' == elt.tagName) { elt.className = 'sf-dump-expanded'; a = elt.previousSibling || {}; if ('A' !=
a.tagName) { a = doc.createElement('A'); a.className = 'sf-dump-ref';
elt.parentNode.insertBefore(a, elt); } else { a.innerHTML += ' '; }
a.title = (a.title ? a.title+'\n[' : '[')+keyHint+'+click] Expand all
children'; a.innerHTML += '▼'; a.className += '
sf-dump-toggle'; x = 1; if ('sf-dump' != elt.parentNode.className) { x
+= elt.parentNode.getAttribute('data-depth')/1; } elt.setAttribute('data-depth', x); if (x > options.maxDepth) {
toggle(a); } } else if (/\bsf-dump-ref\b/.test(elt.className) && (a =
elt.getAttribute('href'))) { a = a.substr(1); elt.className += ' '+a;
if (/[[{]$/.test(elt.previousSibling.nodeValue)) { a = a !=
elt.nextSibling.id && doc.getElementById(a); try { s = a.nextSibling;
elt.appendChild(a); s.parentNode.insertBefore(a, s); if
(/^[##]/.test(elt.innerHTML)) { elt.innerHTML += '
▶'; } else { elt.innerHTML =
'▶'; elt.className = 'sf-dump-ref'; } elt.className
+= ' sf-dump-toggle'; } catch (e) { if ('&' == elt.innerHTML.charAt(0)) { elt.innerHTML = '…'; elt.className =
'sf-dump-ref'; } } } } } if (doc.evaluate && Array.from &&
root.children.length > 1) { root.setAttribute('tabindex', 0);
SearchState = function () { this.nodes = []; this.idx = 0; };
SearchState.prototype = { next: function () { if (this.isEmpty()) {
return this.current(); } this.idx = this.idx < (this.nodes.length - 1)
? this.idx + 1 : this.idx; return this.current(); }, previous:
function () { if (this.isEmpty()) { return this.current(); } this.idx
= this.idx > 0 ? this.idx - 1 : this.idx; return this.current(); }, isEmpty: function () { return 0 === this.count(); }, current: function
() { if (this.isEmpty()) { return null; } return this.nodes[this.idx];
}, reset: function () { this.nodes = []; this.idx = 0; }, count:
function () { return this.nodes.length; }, }; function
showCurrent(state) { var currentNode = state.current(); if
(currentNode) { reveal(currentNode); highlight(root, currentNode,
state.nodes); } counter.textContent = (state.isEmpty() ? 0 : state.idx
+ 1) + ' of ' + state.count(); } var search = doc.createElement('div'); search.className = 'sf-dump-search-wrapper
sf-dump-search-hidden'; search.innerHTML = ' 0 of
0</span> </svg> </button> </svg> </button> '; root.insertBefore(search, root.firstChild); var state = new SearchState(); var searchInput =
search.querySelector('.sf-dump-search-input'); var counter =
search.querySelector('.sf-dump-search-count'); var searchInputTimer =
0; var previousSearchQuery = ''; addEventListener(searchInput,
'keyup', function (e) { var searchQuery = e.target.value; / Don't
perform anything if the pressed key didn't change the query / if
(searchQuery === previousSearchQuery) { return; } previousSearchQuery
= searchQuery; clearTimeout(searchInputTimer); searchInputTimer = setTimeout(function () { state.reset(); collapseAll(root);
resetHighlightedNodes(root); if ('' === searchQuery) {
counter.textContent = '0 of 0'; return; } var xpathResult =
doc.evaluate('//pre[#id="' + root.id + '"]//span[#class="sf-dump-str"
or #class="sf-dump-key" or #class="sf-dump-public" or
#class="sf-dump-protected" or
#class="sf-dump-private"][contains(child::text(), ' +
xpathString(searchQuery) + ')]', document, null,
XPathResult.ORDERED_NODE_ITERATOR_TYPE, null); while (node =
xpathResult.iterateNext()) state.nodes.push(node); showCurrent(state);
}, 400); });
Array.from(search.querySelectorAll('.sf-dump-search-input-next,
.sf-dump-search-input-previous')).forEach(function (btn) {
addEventListener(btn, 'click', function (e) { e.preventDefault(); -1
!== e.target.className.indexOf('next') ? state.next() :
state.previous(); searchInput.focus(); collapseAll(root);
showCurrent(state); }) }); addEventListener(root, 'keydown', function
(e) { var isSearchActive =
!/\bsf-dump-search-hidden\b/.test(search.className); if ((114 ===
e.keyCode && !isSearchActive) || (isCtrlKey(e) && 70 === e.keyCode)) {
/ F3 or CMD/CTRL + F / e.preventDefault(); search.className =
search.className.replace(/\bsf-dump-search-hidden\b/, '');
searchInput.focus(); } else if (isSearchActive) { if (27 ===
e.keyCode) { / ESC key / search.className += '
sf-dump-search-hidden'; e.preventDefault();
resetHighlightedNodes(root); searchInput.value = ''; } else if (
(isCtrlKey(e) && 71 === e.keyCode) / CMD/CTRL + G / || 13 ===
e.keyCode / Enter / || 114 === e.keyCode / F3 */ ) {
e.preventDefault(); e.shiftKey ? state.previous() : state.next();
collapseAll(root); showCurrent(state); } } }); } if (0 >=
options.maxStringLength) { return; } try { elt =
root.querySelectorAll('.sf-dump-str'); len = elt.length; i = 0; t =
[]; while (i < len) t.push(elt[i++]); len = t.length; for (i = 0; i <
len; ++i) { elt = t[i]; s = elt.innerText || elt.textContent; x =
s.length - options.maxStringLength; if (0 < x) { h = elt.innerHTML;
elt[elt.innerText ? 'innerText' : 'textContent'] = s.substring(0,
options.maxStringLength); elt.className += ' sf-dump-str-collapse';
elt.innerHTML = ''+h+'
◀'+ ''+elt.innerHTML+'
▶'; } } } catch (e) { } }; })(document);
pre.sf-dump { display: block; white-space: pre;
padding: 5px; } pre.sf-dump:after { content: ""; visibility: hidden;
display: block; height: 0; clear: both; } pre.sf-dump span { display:
inline; } pre.sf-dump .sf-dump-compact { display: none; } pre.sf-dump
abbr { text-decoration: none; border: none; cursor: help; }
pre.sf-dump a { text-decoration: none; cursor: pointer; border: 0;
outline: none; color: inherit; } pre.sf-dump .sf-dump-ellipsis {
display: inline-block; overflow: visible; text-overflow: ellipsis;
max-width: 5em; white-space: nowrap; overflow: hidden; vertical-align:
top; } pre.sf-dump .sf-dump-ellipsis+.sf-dump-ellipsis { max-width:
none; } pre.sf-dump code { display:inline; padding:0; background:none;
} .sf-dump-str-collapse .sf-dump-str-collapse { display: none; }
.sf-dump-str-expand .sf-dump-str-expand { display: none; }
.sf-dump-public.sf-dump-highlight,
.sf-dump-protected.sf-dump-highlight,
.sf-dump-private.sf-dump-highlight, .sf-dump-str.sf-dump-highlight,
.sf-dump-key.sf-dump-highlight { background: rgba(111, 172, 204, 0.3);
border: 1px solid #7DA0B1; border-radius: 3px; }
.sf-dump-public.sf-dump-highlight-active,
.sf-dump-protected.sf-dump-highlight-active,
.sf-dump-private.sf-dump-highlight-active,
.sf-dump-str.sf-dump-highlight-active,
.sf-dump-key.sf-dump-highlight-active { background: rgba(253, 175, 0,
0.4); border: 1px solid #ffa500; border-radius: 3px; } pre.sf-dump .sf-dump-search-hidden { display: none; } pre.sf-dump
.sf-dump-search-wrapper { float: right; font-size: 0; white-space:
nowrap; max-width: 100%; text-align: right; } pre.sf-dump
.sf-dump-search-wrapper > * { vertical-align: top; box-sizing:
border-box; height: 21px; font-weight: normal; border-radius: 0;
background: #FFF; color: #757575; border: 1px solid #BBB; }
pre.sf-dump .sf-dump-search-wrapper > input.sf-dump-search-input {
padding: 3px; height: 21px; font-size: 12px; border-right: none;
width: 140px; border-top-left-radius: 3px; border-bottom-left-radius:
3px; color: #000; } pre.sf-dump .sf-dump-search-wrapper >
.sf-dump-search-input-next, pre.sf-dump .sf-dump-search-wrapper >
.sf-dump-search-input-previous { background: #F2F2F2; outline: none;
border-left: none; font-size: 0; line-height: 0; } pre.sf-dump
.sf-dump-search-wrapper > .sf-dump-search-input-next {
border-top-right-radius: 3px; border-bottom-right-radius: 3px; }
pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-input-next >
svg, pre.sf-dump .sf-dump-search-wrapper >
.sf-dump-search-input-previous > svg { pointer-events: none; width:
12px; height: 12px; } pre.sf-dump .sf-dump-search-wrapper >
.sf-dump-search-count { display: inline-block; padding: 0 5px; margin:
0; border-left: none; line-height: 21px; font-size: 12px;
}pre.sf-dump, pre.sf-dump .sf-dump-default{background-color:#fff;
color:#222; line-height:1.2em; font-weight:normal; font:12px Monaco,
Consolas, monospace; word-wrap: break-word; white-space: pre-wrap;
position:relative; z-index:100000}pre.sf-dump
.sf-dump-num{color:#a71d5d}pre.sf-dump
.sf-dump-const{color:#795da3}pre.sf-dump
.sf-dump-str{color:#df5000}pre.sf-dump
.sf-dump-cchr{color:#222}pre.sf-dump
.sf-dump-note{color:#a71d5d}pre.sf-dump
.sf-dump-ref{color:#a0a0a0}pre.sf-dump
.sf-dump-public{color:#795da3}pre.sf-dump
.sf-dump-protected{color:#795da3}pre.sf-dump
.sf-dump-private{color:#795da3}pre.sf-dump
.sf-dump-meta{color:#b729d9}pre.sf-dump
.sf-dump-key{color:#df5000}pre.sf-dump
.sf-dump-index{color:#a71d5d}array:1 [ "serialnumber" => "ASDQ13"]Sfdump("sf-dump-2124159715")
You need to use
return $request->all();
instead of
dd($request->all());
in your controller function.
return $request->all(); just return the response with your $request data.
Hope this helps you!
I am coding a page that increments the CSS top and left properties in order to simulate an animation with two stars moving around a button. I calculated the measurements, and it looked fine at first. However, after several minutes, the stars become desynchronized, and don't change animation at the same time. They should be reaching a corner at the same time. Can someone please explain why this is, and how I could fix it? My JSFiddle is here: https://jsfiddle.net/MCBlastoise/1503x4tr/12/
And here is my code:
body {
margin:0px;
}
.heading {
text-align:center;
font-family:'Bungee Shade', Courier New, Courier, Lucida Sans Typewriter, Lucida Typewriter, monospace;
color:green;
font-weight:bold;
font-size:30px;
margin-top:0px;
}
.text {
color:red;
font-family:'Josefin Sans', Futura, Trebuchet MS, Arial, sans-serif;
font-size:21px;
text-align:justify;
margin-top:-15px;
}
br {
line-height:500%;
}
.container {
position:relative;
width:350px;
height:350px;
margin-top:42px;
margin-left:auto;
margin-right:auto;
}
.star {
width:40px;
height:40px;
position:absolute;
}
#starOne {
top:0px;
left:0px;
}
#starTwo {
top:310px;
left:310px;
}
.button {
width:250px;
height:250px;
border-style:solid;
border-color:red;
border-width:5px;
border-radius:60px;
text-align:center;
position:absolute;
bottom:50px;
left:50px;
}
.button:hover {
background-color: #7CFC00;
cursor:pointer
}
.button-text {
font-family:'Righteous', Courier New;
color:#9400D3;
font-size:76px;
line-height:125%;
}
#compliment {
text-align:center;
font-family:'VT323', Candara, Calibri, Segoe, Segoe UI, Optima, Arial, sans-serif;
color:#ffd400;
font-size:50px;
}
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="Complement.css">
<link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Bungee+Shade|Josefin+Sans|VT323|Righteous">
<title>The Compliment Machine</title>
</head>
<body>
<h2 class="heading">The Compliment Machine</h2>
<p class="text">In the interest of spreading holiday cheer, I have designed this website with one goal in mind. Pressing the button below will randomly generate a compliment. Hopefully, this little experiment will brighten up your day.</p>
<div class="container" id="container">
<img src="Star.png" class="star" id="starOne">
<div class="button" onclick="timedFunction()" onmouseenter="startingFunction(), startingFunction2()" onmouseleave="endFunction()"> <span class="button-text">Click me!</span> </div>
<img src="Star.png" class="star" id="starTwo">
</div>
<br>
<p id="compliment"></p>
<script>
var userName = prompt("What is your name?");
var generatedUserName = userName === null || userName === "";
var compliment = [
"Have a nice day",
"you contribute to society",
"Always be yourself",
"you are a wonderful person",
"Keep up the good work",
"never stop believing in yourself",
"you have a great sense of humor",
"You should feel proud of yourself",
"Never stop trying",
"you are a winner"
];
</script>
<script>
function timedFunction() {
document.getElementsByTagName("DIV")[0].style.display = "none";
document.getElementsByTagName("DIV")[1].style.display = "none";
document.getElementsByTagName("IMG")[0].style.display = "none";
document.getElementsByTagName("IMG")[1].style.display = "none";
var repeater = setInterval(inspiration, 1000);
}
var inspiration = function inspire() {
var result = Math.random();
//This code block checks for null, undefined, and other falsy values in the prompt.
if (generatedUserName) {
if (0 <= result && result < 0.11) {
userName = "my friend";
}
if (0.21 <= result && result < 0.31) {
userName = "my friend";
}
if (0.41 <= result && result < 0.51) {
userName = "my friend";
}
if (0.71 <= result && result < 0.81) {
userName = "my friend";
}
if (0.81 <= result && result < 0.91) {
userName = "my friend";
}
if (0.11 <= result && result < 0.21) {
userName = "My friend";
}
if (0.31 <= result && result < 0.41) {
userName = "My friend";
}
if (0.51 <= result && result < 0.61) {
userName = "My friend";
}
if (0.61 <= result && result < 0.71) {
userName = "My friend";
}
if (0.91 <= result && result < 1) {
userName = "My friend";
}
}
//This code block changes the sentence with ID 'compliment' randomly, based on the value of the variable 'result'.
if (0 <= result && result < 0.11) {
document.getElementById("compliment").innerHTML = compliment[0]+", "+userName+"!";
};
if (0.11 <= result && result < 0.21) {
document.getElementById("compliment").innerHTML = userName+", "+compliment[1]+".";
};
if (0.21 <= result && result < 0.31) {
document.getElementById("compliment").innerHTML = compliment[2]+", "+userName+".";
};
if (0.31 <= result && result < 0.41) {
document.getElementById("compliment").innerHTML = userName+", "+compliment[3]+".";
};
if (0.41 <= result && result < 0.51) {
document.getElementById("compliment").innerHTML = compliment[4]+", "+userName+"!";
};
if (0.51 <= result && result < 0.61) {
document.getElementById("compliment").innerHTML = userName+", "+compliment[5]+".";
};
if (0.61 <= result && result < 0.71) {
document.getElementById("compliment").innerHTML = userName+", "+compliment[6]+".";
};
if (0.71 <= result && result < 0.81) {
document.getElementById("compliment").innerHTML = compliment[7]+", "+userName+".";
};
if (0.81 <= result && result < 0.91) {
document.getElementById("compliment").innerHTML = compliment[8]+", "+userName+".";
};
if (0.91 <= result && result < 1) {
document.getElementById("compliment").innerHTML = userName+", "+compliment[9]+".";
};
}
var i = 0;
function limitedFunction() {
inspiration();
i++;
if (i === 5) {
document.getElementsByTagName("DIV")[0].style.display = "none";
document.getElementsByTagName("DIV")[1].style.display = "none";
document.getElementsByTagName("IMG")[0].style.display = "none";
document.getElementsByTagName("IMG")[1].style.display = "none";
}
}
</script>
<script>
var starOne = document.getElementById("starOne");
var starTwo = document.getElementById("starTwo");
var posLeft = 0;
var posTop = 0;
var posLeft2 = 310;
var posTop2 = 310;
var startingFunction = function starterFunction() {
toRight = setInterval(moveRight, 1);
}
var startingFunction2 = function starterFunction2() {
toLeft = setInterval(moveLeft, 1);
}
//The following four functions apply to the first star, which begins at the top-left.
function moveRight() {
posLeft++;
starOne.style.left = posLeft + 'px';
if (starOne.style.left === "310px") {
clearInterval(toRight);
toBottom = setInterval(moveDown, 1);
}
}
function moveDown() {
posTop++;
starOne.style.top = posTop + 'px';
if (starOne.style.top === "310px") {
clearInterval(toBottom);
toLeft2 = setInterval(moveLeft2, 1);
}
}
function moveLeft2() {
posLeft--;
starOne.style.left = posLeft + 'px';
if (starOne.style.left === "0px") {
clearInterval(toLeft2);
toTop2 = setInterval(moveUp2, 1);
}
}
function moveUp2() {
posTop--;
starOne.style.top = posTop + 'px';
if (starOne.style.top === "0px") {
clearInterval(toTop2);
startingFunction();
}
}
//The following four functions apply to the second star, which begins at the bottom-right.
function moveLeft() {
posLeft2--;
starTwo.style.left = posLeft2 + 'px';
if (starTwo.style.left === "0px") {
clearInterval(toLeft);
toTop = setInterval(moveUp, 1);
}
}
function moveUp() {
posTop2--;
starTwo.style.top = posTop2 + 'px';
if (starTwo.style.top === "0px") {
clearInterval(toTop);
toRight2 = setInterval(moveRight2, 1);
}
}
function moveRight2() {
posLeft2++;
starTwo.style.left = posLeft2 + 'px';
if (starTwo.style.left === "310px") {
clearInterval(toRight2);
toBottom2 = setInterval(moveDown2, 1);
}
}
function moveDown2() {
posTop2++;
starTwo.style.top = posTop2 + 'px';
if (starTwo.style.top === "310px") {
clearInterval(toBottom2);
startingFunction2();
}
}
//The following function cancels the animation when the mouse leaves the button.
function endFunction() {
//The following four if statements apply to the first star, which begins in the top-left.
if (0 <= posLeft && posLeft <= 310 && posTop === 0) {
clearInterval(toRight);
}
if (0 <= posTop && posTop <= 310 && posLeft === 310) {
clearInterval(toBottom);
}
if (0 <= posLeft && posLeft <= 310 && posTop === 310) {
clearInterval(toLeft2);
}
if (0 <= posTop && posTop <= 310 && posLeft === 0) {
clearInterval(toTop2);
}
//The following four if statements apply to the second star, which begins in the bottom-right.
if (0 <= posLeft2 && posLeft2 <= 310 && posTop2 === 310) {
clearInterval(toLeft);
}
if (0 <= posTop2 && posTop2 <= 310 && posLeft2 === 0) {
clearInterval(toTop);
}
if (0 <= posLeft2 && posLeft2 <= 310 && posTop2 === 0) {
clearInterval(toRight2);
}
if (0 <= posTop2 && posTop2 <= 310 && posLeft2 === 310) {
clearInterval(toBottom2);
}
posLeft = 0;
posTop = 0;
posLeft2 = 310;
posTop2 = 310;
starOne.style.top = posTop + 'px';
starOne.style.left = posLeft + 'px';
starTwo.style.top = posTop2 + 'px';
starTwo.style.left = posLeft2 + 'px';
}
</script>
</body>
</html>
How about you use an alternative approach i.e. use css animation property for the animation and don't use setInterval at all.
Use the keyframes and animate the stars on hover. Here is the working example
var starOne = document.getElementById("starOne");
var starTwo = document.getElementById("starTwo");
var posLeft = 0;
var posTop = 0;
var posLeft2 = 310;
var posTop2 = 310;
document.getElementById("btn").addEventListener("mouseover",function(){
starOne.classList.add("topStarAnimate");
starTwo.classList.add("bottomStarAnimate");
});
document.getElementById("btn").addEventListener("mouseleave",function(){
starOne.classList.remove("topStarAnimate");
starTwo.classList.remove("bottomStarAnimate");
});
body {
margin:0px;
}
.heading {
text-align:center;
font-family:'Bungee Shade', Courier New, Courier, Lucida Sans Typewriter, Lucida Typewriter, monospace;
color:green;
font-weight:bold;
font-size:30px;
margin-top:0px;
}
.text {
color:red;
font-family:'Josefin Sans', Futura, Trebuchet MS, Arial, sans-serif;
font-size:21px;
text-align:justify;
margin-top:-15px;
}
br {
line-height:500%;
}
.container {
position:relative;
width:350px;
height:350px;
margin-top:42px;
margin-left:auto;
margin-right:auto;
}
.star {
width:40px;
height:40px;
position:absolute;
}
#starOne {
top:0px;
left:0px;
}
#starTwo {
top:310px;
left:310px;
}
#keyframes topstar {
0%,100%{
top:0px;
left:0px;
}
25%{
top:0px;
left:310px;
}
50%{
top:310px;
left:310px;
}
75%{
top:310px;
left:0px;
}
}
#keyframes bottomstar {
0%,100%{
top:310px;
left:310px;
}
25%{
top:310px;
left:0px;
}
50%{
top:0px;
left:0px;
}
75%{
top:0px;
left:310px;
}
}
.topStarAnimate{
animation: topstar 4s infinite;
}
.bottomStarAnimate{
animation: bottomstar 4s infinite;
}
.button {
width:250px;
height:250px;
border-style:solid;
border-color:red;
border-width:5px;
border-radius:60px;
text-align:center;
position:absolute;
bottom:50px;
left:50px;
}
.button:hover {
background-color: #7CFC00;
cursor:pointer
}
.button-text {
font-family:'Righteous', Courier New;
color:#9400D3;
font-size:76px;
line-height:125%;
}
<!DOCTYPE html>
<title>The Compliment Machine</title>
<body>
<div class="container" id="container">
<img src="Star.png" class="star" id="starOne">
<div class="button" onclick="timedFunction()" id="btn"> <span class="button-text">Click me!</span> </div>
<img src="Star.png" class="star" id="starTwo">
</div>
<br>
<p id="compliment"></p>
</body>
I’m trying to create a virtual phone keypad with alphabet feature for SMS. This is what I’ve tried so far:
var button = document.querySelectorAll('button'),
input = document.querySelector('input'),
busy = true,
hold,
is_busy,
delay = 1000,
change = -1,
click = null;
for (var i = 0, len = button.length; i < len; ++i) {
button[i].onmousedown = function(e) {
var text = this.getAttribute('data-text').split(""),
number = this.getAttribute('data-number');
busy = true;
clearTimeout(is_busy);
if (click !== e.target) {
busy = false;
}
if (change >= text.length - 1 || click !== e.target) {
change = 0;
click = e.target;
} else {
change = change + 1;
}
if (text[0] === '#') {
input.value = input.value.slice(0, -1);
hold = setTimeout(function() {
input.value = "";
}, delay);
return;
}
hold = setTimeout(function() {
input.value = input.value.slice(0, -1) + number;
}, delay);
input.value = busy ? input.value.slice(0, -1) + text[change] : input.value + text[change];
};
button[i].onmouseup = function(e) {
clearTimeout(hold);
busy = true;
is_busy = setTimeout(function() {
change = -1;
busy = false;
e.target = null;
}, delay);
// put caret at the end of text input
input.focus();
input.selectionStart = input.selectionEnd = input.value.length;
};
}
<p>
<input type="text">
</p>
<p>
<button data-text=".,?!'"1-()#/:_" data-number="1">1 <small>o_o</small></button>
<button data-text="abc2" data-number="2">2 <small>abc</small></button>
<button data-text="def3" data-number="3">3 <small>def</small></button>
</p>
<p>
<button data-text="ghi4" data-number="4">4 <small>ghi</small></button>
<button data-text="jkl5" data-number="5">5 <small>jkl</small></button>
<button data-text="mno6" data-number="6">6 <small>mno</small></button>
</p>
<p>
<button data-text="pqrs7" data-number="7">7 <small>pqrs</small></button>
<button data-text="tuv8" data-number="8">8 <small>tuv</small></button>
<button data-text="wxyz9" data-number="9">9 <small>wxyz</small></button>
</p>
<p>
<button data-text=" 0" data-number="0">0 <small>__</small></button>
<button data-text="#">←</button>
</p>
The results are almost in line as I expected, just lacking a few minor things. The following are the requirements:
Pressing the same button quickly will replace the last character without adding more characters. OK
Switch to another button will add new character. OK
Press and hold the button until delay will replace the last character to a number. OK
Pressing the same button quickly will replace the last character without adding more characters, wait until delay, then press again. It should add a new character at the end. NO
Thank’s for your help.
I create a keypad as well, you can take some suggestion from it. I did not use the setTimeOut function but I opt-in for a onmouseleave eventListner, so when you leave the div, the last letter that you choise will appear on the display. Also I did not include the numbers yet...still to add stuff, but I hope it will help.
let numbers = new Array(11);
numbers[0] = "1";
numbers[1] = "2";
numbers[2] = "3";
numbers[3] = "4";
numbers[4] = "5";
numbers[5] = "6";
numbers[6] = "7";
numbers[7] = "8";
numbers[8] = "9";
numbers[9] = "*";
numbers[10] = "0";
numbers[11] = "#";
let letter = new Array(11);
letter[0] = "o_o";
letter[1] = "abc";
letter[2] = "def";
letter[3] = "ghi";
letter[4] = "jkl";
letter[5] = "mno";
letter[6] = "pqrs";
letter[7] = "tuv";
letter[8] = "wxyz";
letter[9] = "+";
letter[10] = "_";
letter[11] = "↑";
let text = "";
let counter = 0;
let clicked = false;
// function to create the 12 div ( keypad buttons ). In the div I put the onclick function run() and I assign them a class and Id to style it in CSS.
// also every 3 div, the next div will appear in the second line to create a keypad style.
function start()
{
let div_content ="";
for (i=0; i<=11; i++)
{
let element = "number" + i;
div_content = div_content + '<div class="letter" onclick="run('+i+')" id="'+element+'">'+numbers[i]+'<br>'+letter[i]+'</div>';
if ((i+1) % 3 ==0) div_content = div_content + '<div style="clear:both;"></div>';
}
document.getElementById("key_cont").innerHTML = div_content;
}
//////////////////////////////////////////////////////////////////////Operating Script//////////////////////////////////////////////////
//function run will be activated when any of the div-button will be pressed, nr function argument will indicate which of the button has been pressed.
function run(nr) {
//for loop to assign addEventListener onmouseleave to all the buttons. it will activate the choiseAndReset function that will show the result on
//the display and will go to the next position in a way to choise another letter.
for (i=0; i<=11; i++)
{
let element = "number" + i;
document.getElementById(element).addEventListener("mouseleave", choiseAndReset);
}
//switch will check which div button has been pressed and will display the correct letter. Inside the cases there are two if.
//one to check the counter ( to check which letter need to be displayed )
//the second one is to check if the capital letter button is clicked, if yes, all the next letters will be Capital letter till will not be deactivated.
switch (nr) {
case 0:
counter ++;
if(counter >= 6) {
counter = 1;
text = text.toString().replace(/.$/,".");
document.getElementById("screen").value = text;
//return counter;
}
else {
if (counter % 3 == 0) {
text = text.toString().replace(/.$/,"?");
document.getElementById("screen").value = text;
}
else if (counter % 4 == 0){
text = text.toString().replace(/.$/,"!");
document.getElementById("screen").value = text;
}
else if (counter % 5 == 0){
text = text.toString().replace(/.$/,"'");
document.getElementById("screen").value = text;
}
else if (counter % 2 == 0) {
text = text.toString().replace(/.$/,",");
document.getElementById("screen").value = text;
}
else {
text += ".";
document.getElementById("screen").value = text;
}
}
break;
case 1:
counter ++;
if(counter >= 4) {
if( clicked == true ) {
counter = 1;
text = text.toString().replace(/.$/,"A");
document.getElementById("screen").value = text;
}
else {
counter = 1;
text = text.toString().replace(/.$/,"a");
document.getElementById("screen").value = text;
}
}
else {
if (counter % 3 == 0) {
if( clicked == true ) {
text = text.toString().replace(/.$/,"C");
document.getElementById("screen").value = text;
}
else {
text = text.toString().replace(/.$/,"c");
document.getElementById("screen").value = text;
}
}
else if (counter % 2 == 0) {
if( clicked == true ) {
text = text.toString().replace(/.$/,"B");
document.getElementById("screen").value = text;
}
else {
text = text.toString().replace(/.$/,"b");
document.getElementById("screen").value = text;
}
}
else {
if( clicked == true ) {
text += "A";
document.getElementById("screen").value = text;
}
else {
text += "a";
document.getElementById("screen").value = text;
}
}
}
break;
case 2:
counter ++;
if(counter >= 4) {
if( clicked == true ) {
counter = 1;
text = text.toString().replace(/.$/,"D");
document.getElementById("screen").value = text;
}
else {
counter = 1;
text = text.toString().replace(/.$/,"d");
document.getElementById("screen").value = text;
}
}
else {
if (counter % 3 == 0) {
if( clicked == true ) {
text = text.toString().replace(/.$/,"F");
document.getElementById("screen").value = text;
}
else {
text = text.toString().replace(/.$/,"f");
document.getElementById("screen").value = text;
}
}
else if (counter % 2 == 0) {
if( clicked == true ) {
text = text.toString().replace(/.$/,"E");
document.getElementById("screen").value = text;
}
else {
text = text.toString().replace(/.$/,"e");
document.getElementById("screen").value = text;
}
}
else {
if( clicked == true ) {
text += "D";
document.getElementById("screen").value = text;
}
else {
text += "d";
document.getElementById("screen").value = text;
}
}
}
break;
case 3:
counter ++;
if(counter >= 4) {
if( clicked == true ) {
counter = 1;
text = text.toString().replace(/.$/,"G");
document.getElementById("screen").value = text;
}
else {
counter = 1;
text = text.toString().replace(/.$/,"g");
document.getElementById("screen").value = text;
}
}
else {
if (counter % 3 == 0) {
if( clicked == true ) {
text = text.toString().replace(/.$/,"I");
document.getElementById("screen").value = text;
}
else {
text = text.toString().replace(/.$/,"i");
document.getElementById("screen").value = text;
}
}
else if (counter % 2 == 0) {
if( clicked == true ) {
text = text.toString().replace(/.$/,"H");
document.getElementById("screen").value = text;
}
else {
text = text.toString().replace(/.$/,"h");
document.getElementById("screen").value = text;
}
}
else {
if( clicked == true ) {
text += "G";
document.getElementById("screen").value = text;
}
else {
text += "g";
document.getElementById("screen").value = text;
}
}
}
break;
case 4:
counter ++;
if(counter >= 4) {
if( clicked == true ) {
counter = 1;
text = text.toString().replace(/.$/,"J");
document.getElementById("screen").value = text;
}
else {
counter = 1;
text = text.toString().replace(/.$/,"j");
document.getElementById("screen").value = text;
}
}
else {
if (counter % 3 == 0) {
if( clicked == true ) {
text = text.toString().replace(/.$/,"L");
document.getElementById("screen").value = text;
}
else {
text = text.toString().replace(/.$/,"l");
document.getElementById("screen").value = text;
}
}
else if (counter % 2 == 0) {
if( clicked == true ) {
text = text.toString().replace(/.$/,"K");
document.getElementById("screen").value = text;
}
else {
text = text.toString().replace(/.$/,"k");
document.getElementById("screen").value = text;
}
}
else {
if( clicked == true ) {
text += "J";
document.getElementById("screen").value = text;
}
else {
text += "j";
document.getElementById("screen").value = text;
}
}
}
break;
case 5:
counter ++;
if(counter >= 4) {
if( clicked == true ) {
counter = 1;
text = text.toString().replace(/.$/,"M");
document.getElementById("screen").value = text;
}
else {
counter = 1;
text = text.toString().replace(/.$/,"m");
document.getElementById("screen").value = text;
}
}
else {
if (counter % 3 == 0) {
if( clicked == true ) {
text = text.toString().replace(/.$/,"O");
document.getElementById("screen").value = text;
}
else {
text = text.toString().replace(/.$/,"o");
document.getElementById("screen").value = text;
}
}
else if (counter % 2 == 0) {
if( clicked == true ) {
text = text.toString().replace(/.$/,"N");
document.getElementById("screen").value = text;
}
else {
text = text.toString().replace(/.$/,"n");
document.getElementById("screen").value = text;
}
}
else {
if( clicked == true ) {
text += "M";
document.getElementById("screen").value = text;
}
else {
text += "m";
document.getElementById("screen").value = text;
}
}
}
break;
case 6:
counter ++;
if(counter >= 5) {
if( clicked == true ) {
counter = 1;
text = text.toString().replace(/.$/,"P");
document.getElementById("screen").value = text;
}
else {
counter = 1;
text = text.toString().replace(/.$/,"p");
document.getElementById("screen").value = text;
}
}
else {
if (counter % 3 == 0) {
if( clicked == true ) {
text = text.toString().replace(/.$/,"R");
document.getElementById("screen").value = text;
}
else {
text = text.toString().replace(/.$/,"r");
document.getElementById("screen").value = text;
}
}
else if (counter % 4 == 0){
if( clicked == true ) {
text = text.toString().replace(/.$/,"S");
document.getElementById("screen").value = text;
}
else {
text = text.toString().replace(/.$/,"s");
document.getElementById("screen").value = text;
}
}
else if (counter % 2 == 0) {
if( clicked == true ) {
text = text.toString().replace(/.$/,"Q");
document.getElementById("screen").value = text;
}
else {
text = text.toString().replace(/.$/,"q");
document.getElementById("screen").value = text;
}
}
else {
if( clicked == true ) {
text += "P";
document.getElementById("screen").value = text;
}
else {
text += "p";
document.getElementById("screen").value = text;
}
}
}
break;
case 7:
counter ++;
if(counter >= 4) {
if( clicked == true ) {
counter = 1;
text = text.toString().replace(/.$/,"T");
document.getElementById("screen").value = text;
}
else {
counter = 1;
text = text.toString().replace(/.$/,"t");
document.getElementById("screen").value = text;
}
}
else {
if (counter % 3 == 0) {
if( clicked == true ) {
text = text.toString().replace(/.$/,"V");
document.getElementById("screen").value = text;
}
else {
text = text.toString().replace(/.$/,"v");
document.getElementById("screen").value = text;
}
}
else if (counter % 2 == 0) {
if( clicked == true ) {
text = text.toString().replace(/.$/,"U");
document.getElementById("screen").value = text;
}
else {
text = text.toString().replace(/.$/,"u");
document.getElementById("screen").value = text;
}
}
else {
if( clicked == true ) {
text += "T";
document.getElementById("screen").value = text;
}
else {
text += "t";
document.getElementById("screen").value = text;
}
}
}
break;
case 8:
counter ++;
if(counter >= 5) {
if( clicked == true ) {
counter = 1;
text = text.toString().replace(/.$/,"W");
document.getElementById("screen").value = text;
}
else {
counter = 1;
text = text.toString().replace(/.$/,"w");
document.getElementById("screen").value = text;
}
}
else {
if (counter % 3 == 0) {
if( clicked == true ) {
text = text.toString().replace(/.$/,"Y");
document.getElementById("screen").value = text;
}
else {
text = text.toString().replace(/.$/,"y");
document.getElementById("screen").value = text;
}
}
else if (counter % 4 == 0){
if( clicked == true ) {
text = text.toString().replace(/.$/,"Z");
document.getElementById("screen").value = text;
}
else {
text = text.toString().replace(/.$/,"z");
document.getElementById("screen").value = text;
}
}
else if (counter % 2 == 0) {
if( clicked == true ) {
text = text.toString().replace(/.$/,"X");
document.getElementById("screen").value = text;
}
else {
text = text.toString().replace(/.$/,"x");
document.getElementById("screen").value = text;
}
}
else {
if( clicked == true ) {
text += "W";
document.getElementById("screen").value = text;
}
else {
text += "w";
document.getElementById("screen").value = text;
}
}
}
break;
case 9:
counter ++;
if(counter >= 1) {
text += "+";
document.getElementById("screen").value = text;
}
break;
case 10:
counter ++;
if(counter >= 1) {
text += " ";
document.getElementById("screen").value = text;
}
break;
case 11:
counter ++;
if (clicked == true ) {
clicked = false;
}
else {
clicked = true;
}
break;
}
function choiseAndReset() {
document.getElementById("screen").value = text;
counter = 0;
return counter;
}
//console.log(counter);
//console.log(clicked);
}
body {
background-color: #253B3B;
color: white;
}
.container {
margin-left: auto;
margin-right: auto;
}
p {
font-size: 35px;
}
#screen {
width: 1000px;
height: 60px;
position: relative;
bottom: 20px;
}
input[type=text]
{
color: #979797;
font-size: 35px;
}
#display {
width: 1200px;
height: 100px;
padding: 10px;
border: 5px solid #BEE5E5;
margin-top: 10px;
text-align: center;
margin-left: auto;
margin-right: auto;
}
#key_cont
{
margin-top: 25px;
width: 450px;
text-align: center;
min-height: 280px;
margin-left: auto;
margin-right: auto;
}
.letter
{
width: 100px;
height: 100px;
text-align:center;
padding: 5px;
margin: 5px;
border: 5px solid gray;
float: left;
cursor: pointer;
border-radius: 15px;
font-size: 40px;
}
.letter:hover
{
background-color: #222222;
color: white;
border: 5px solid white;
}
#number11:active {
background-color:86A3A3;
}
<html>
<head>
<meta charset="UTF-8">
<title>Nokia Keypad</title>
<link rel="stylesheet" href="keypad.css" type="text/css" />
</head>
<body onload="start()">
<div class="container">
<div class="dis" id="display">
<p><input id="screen" type="text" value="Insert your text"></p>
</div>
<div id="key_cont">
</div>
</div>
<script type="text/javascript" src="keypad_final.js"></script>
</body>
</html>