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>
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 tried to create a tic-tac-toe game using minimax algorithm. But before I could write the whole algorithm, I encountered an absurd type of error. This code is for reference in case if you have to look into the full code.
//Using minimax to the same code of tictactoe2.js
$ = document.querySelectorAll(".box");
// adding click event to all boxes
$.forEach((element)=>{
element.addEventListener("click", mainFunction);
})
document.querySelector(".reset-button-container").addEventListener("click", reset);
function mainFunction(e){
if (checkForGameOver() === false){ //once game is over, so should be all clicks
if (e.target.innerText !== ""){
alert("Click Another Square!!!");
}
else{
e.target.innerText = "X";
if (checkForGameOver() === false){ //computer gets its turn only if the game isn't over after players turn
setTimeout(computerTurn, 500);
setTimeout(checkForGameOver, 501); //501 is provided to run checkForGameOver only after computerTurn
}
}
}
}
//a function that randomly plays computers turn
function computerTurn(){
let board = [], bestScore = Infinity, bestMove = {}, k = 0;
//array of innerTexts of each box is the board in one dimension
$.forEach((element, index) => {
board[index] = element.innerText;
});
let board2D = convertToTwoDimension(board, 3, 3); //convert 1d board to 2d of 3 rows and 3 columns
for(i = 0; i < 3; i++){
for(j = 0; j < 3; j++){
if (board2D[i][j] === ""){
board2D[i][j] = "O";
let score = minimax(board2D, false);
board2D[i][j] = "";
if(score < bestScore){
bestScore = score;
bestMove = {i, j};
}
}
}
}
board2D[bestMove.i][bestMove.j] = "O"; //assigning bestMove to baord2D
//to dispaly the played bestMove by the computer on screen
for(i = 0; i < 3; i++){
for(j = 0; j < 3; j++){
$[k].innerText = board2D[i][j];
k += 1;
}
}
}
//minimax implementation
function minimax(position, maximizing){
console.log(position);
//if the game is over at that position, return the score based on who is wining
if (checkForGameOver() === true){
if(document.querySelector(".win-message").innerText[0] === "X"){
return 1; //X (maximizing player) wins
}
else if(document.querySelector(".win-message").innerText[0] === "O"){
return -1; //O (minimizing player) wins
}
else{
return 0; // the game is a draw
}
}
}
//function to check if game is over. But I think it can be written more easily.
function checkForGameOver(){
var tempText = [];
for(i = 1; i <= 9; i++){
tempText[i] = $[i-1].innerText;
}
if (tempText[1] === tempText[2] && tempText[2] === tempText[3] && tempText[1] !== ""){
document.querySelector(".win-message").innerText = tempText[1] + " Wins!!";
return true;
}
else if (tempText[4] === tempText[5] && tempText[5] === tempText[6] && tempText[4] !== ""){
document.querySelector(".win-message").innerText = tempText[4] + " Wins!!";
return true;
}
else if (tempText[7] === tempText[8] && tempText[8] === tempText[9] && tempText[7] !== ""){
document.querySelector(".win-message").innerText = tempText[7] + " Wins!!";
return true;
}
else if (tempText[1] === tempText[4] && tempText[4] === tempText[7] && tempText[1] !== ""){
document.querySelector(".win-message").innerText = tempText[1] + " Wins!!";
return true;
}
else if (tempText[2] === tempText[5] && tempText[5] === tempText[8] && tempText[2] !== ""){
document.querySelector(".win-message").innerText = tempText[2] + " Wins!!";
return true;
}
else if (tempText[3] === tempText[6] && tempText[6] === tempText[9] && tempText[3] !== ""){
document.querySelector(".win-message").innerText = tempText[3] + " Wins!!";
return true;
}
else if (tempText[1] === tempText[5] && tempText[5] === tempText[9] && tempText[1] !== ""){
document.querySelector(".win-message").innerText = tempText[1] + " Wins!!";
return true;
}
else if (tempText[3] === tempText[5] && tempText[5] === tempText[7] && tempText[3] !== ""){
document.querySelector(".win-message").innerText = tempText[3] + " Wins!!";
return true;
}
//if none of above, which is for win only, is true, check for draw which can be done by filtering the remaining blank squares. If no squares are lest, then game is a draw else the game isn't over yet.
else{
arrayOfBlankCharacters = tempText.filter(element => {
return (element === "");
});
if (arrayOfBlankCharacters.length === 0){
document.querySelector(".win-message").innerText = "Game Drawn!!";
return true;
}
else{
return false;
}
}
}
//a function that resets the board and win message.
function reset(){
for(i = 1; i <= 9; i++){
$[i-1].innerText = "";
}
document.querySelector(".win-message").innerText = "";
}
//function to convert 1d array to 2d array => useful for computerTurn() function to access board in 2d view
function convertToTwoDimension(initialArray, rows, columns){
var k = 0, finalArray = [];
for(i = 0; i < initialArray.length/columns; i++){
finalArray[i] = []; //state that each element of finalArray is also an array
for(j = 0; j < initialArray.length/rows; j++){
finalArray[i][j] = initialArray[k];
k += 1;
}
}
return finalArray;
}
#import url('https://fonts.googleapis.com/css2?family=Roboto:wght#900&display=swap');
:root{
font-size: 16px;
font-family: 'Roboto', sans-serif;
}
*, *::after, *::before{
margin: 0;
padding: 0;
box-sizing: border-box;
}
.description-header{
background-color: lightgrey;
line-height: 3rem;
padding-left: 2rem;
margin-bottom: 2rem;
}
.player-information{
text-align: center;
margin-bottom: 1rem;
}
.player-information > h3{
font-size: 2.5rem;
}
.player-information > h3 > span{
color:brown;
}
.game-box-container{
display: flex;
flex-direction: column;
min-height: 100vh;
align-items: center;
}
.tictactoe-box{
height: 250px;
width: 250px;
display: grid;
grid-template: repeat(3, 1fr)/repeat(3, 1fr);
grid-gap: 0.5rem;
background-color: black;
}
.reset-button-container{
margin-top: 1rem;
background: lightgrey;
border-radius: 0.5rem;
}
.tictactoe-box > .box{
display: flex;
justify-content: center;
align-items: center;
font-size: 4rem;
background-color: white;
cursor: context-menu
}
.reset-button-container > span{
display: block;
font-size: 2rem;
padding: 0.5rem 1.5rem;
}
.reset-button-container:hover{
background-color: grey;
cursor: context-menu;
}
.win-message{
margin-top: 1rem;
width: 25%;
font-size: 2.5rem;
background-color: lightgrey;
text-align: center;
border-radius: 10px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>TicTacToe</title>
<link rel="stylesheet" type="text/css" href="tictactoe.css">
<link rel="icon" type="image/x-icon" href="https://upload.wikimedia.org/wikipedia/commons/thumb/3/32/Tic_tac_toe.svg/1024px-Tic_tac_toe.svg.png">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-sclae=1.0">
<meta name="description" content="">
<meta name="keywords" content="">
</head>
<body>
<header class="description-header">
<h3>My TicTacToe Game</h3>
</header>
<div class="player-information">
<h3>Player: "<span>X</span>"; Computer: "<span>O</span>"</h3>
<h3>Player First</h3>
</div>
<div class="game-box-container">
<div class="tictactoe-box">
<div class="box box1"></div>
<div class="box box2"></div>
<div class="box box3"></div>
<div class="box box4"></div>
<div class="box box5"></div>
<div class="box box6"></div>
<div class="box box7"></div>
<div class="box box8"></div>
<div class="box box9"></div>
</div>
<div class="reset-button-container">
<span>Reset</span>
</div>
<div class="win-message">
</div>
</div>
<script type="text/javascript" src="usingMinimax.js"></script>
</body>
</html>
My problem arises in the minimax(position, maximizing) function of the code as below. console.log(position) runs just fine, but because of the checkForGameOver() in the below function, it throws an error that board2D[i] is undefined which is unexpected because there is no any arguments passed in to the checkForGameOver() function. As soon as I remove the (checkForGameOver() === false) condition and run it, the computer makes a move for the first available spot which is as expected.
//minimax implementation
function minimax(position, maximizing){
console.log(position);
//if the game is over at that position, return the score based on who is wining
if (checkForGameOver() === true){
if(document.querySelector(".win-message").innerText[0] === "X"){
return 1; //X (maximizing player) wins
}
else if(document.querySelector(".win-message").innerText[0] === "O"){
return -1; //O (minimizing player) wins
}
else{
return 0; // the game is a draw
}
}
}
A function that doesn't take any variable as arguments just returns a boolean value, is somehow the cause of an error that the variable is undefined.
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
}
I am having an issue with the .className on both getWeight.length < 1 and getHeight.length < 1, its not adding the class name formValidation.
Any ideas why it's not working? I have been staring at the code for so long I can't seem to figure out what's going on!
Many thanks
JS
function calculateBMI() {
let getWeight = document.getElementById('weight').value;
let getHeight = document.getElementById('height').value;
let getBMI = (getWeight / (getHeight*getHeight)).toFixed(2);
let displayBMI = document.getElementById('displaybmi');
if (getWeight.length < 1) {
//alert('Please enter your weight');
getWeight.className = 'formValidation';
}
else if (getHeight.length < 1) {
//alert('Please enter your height');
getHeight.className = 'formValidation';
}
else if(getBMI < 18.5) {
displayBMI.className = 'displaybmi green';
displayBMI.textContent = 'You\'re under weight! ' + getBMI;
}
else if (getBMI >= 18.5 && getBMI <= 25) {
displayBMI.className = 'displaybmi green';
displayBMI.textContent = 'You\'re normal weight! ' + getBMI;
}
else if (getBMI > 25 && getBMI <= 29.99) {
displayBMI.className = 'displaybmi yellow';
displayBMI.textContent = 'You\'re over weight! ' + getBMI;
}
else if (getBMI >= 30 && getBMI <= 34.99) {
displayBMI.className = 'displaybmi orange';
displayBMI.textContent = 'You\'re obese! ' + getBMI;
}
else {
displayBMI.className = 'displaybmi red';
displayBMI.textContent = 'You\'re very obese! ' + getBMI;
}
}
.displaybmi {
font-size: 16px;
padding: 20px;
margin-bottom:20px;
}
.red{
background:red;
}
.yellow {
background: yellow;
}
.green{
background:green;
}
.orange {
background:orange;
}
.formValidation {
border: 2px solid red;
}
You are trying to add classname to value of element (input, I suppose).
getWeight and getHeight are values, not DOM actual elements.
Try:
let getWeight = document.getElementById('weight');
let getHeight = document.getElementById('height');
let getBMI = (getWeight.value / (getHeight.value*getHeight.value)).toFixed(2);
if (getWeight.value.length < 1) {
//alert('Please enter your weight');
getWeight.className = 'formValidation';
}
else if (getHeight.value.length < 1) {
//alert('Please enter your height');
getHeight.className = 'formValidation';
}
CodePen here
The following code opens a pop-up when the page loads (body onload). When a user has closed the pop-up, I don't want it to appear again. This can be done with cookies as far as I have understood, but how can it be added to this example?
<html>
<head>
<title>Popup</title>
<style type="text/css">
#blanket {
display:none;
background-color:#111;
opacity: 0.65;
*background:none;
position:absolute;
z-index: 9001;
top:0px;
left:0px;
width:100%;
}
#popUpDiv {
display:none;
position:fixed;
width:600px;
height:400px;
border:5px solid #000;
z-index: 9002;
padding: 16px;
border: 5px solid #50563C;
border-radius:15px;
background-color: #FFFFFF;
}
</style>
<script type="text/javascript">
function toggle(div_id) {
var el = document.getElementById(div_id);
if ( el.style.display == 'none' ) { el.style.display = 'block';}
else {el.style.display = 'none';}
}
function blanket_size(popUpDivVar) {
if (typeof window.innerWidth != 'undefined') {
viewportheight = window.innerHeight;
} else {
viewportheight = document.documentElement.clientHeight;
}
if ((viewportheight > document.body.parentNode.scrollHeight) && (viewportheight > document.body.parentNode.clientHeight)) {
blanket_height = viewportheight;
} else {
if (document.body.parentNode.clientHeight > document.body.parentNode.scrollHeight) {
blanket_height = document.body.parentNode.clientHeight;
} else {
blanket_height = document.body.parentNode.scrollHeight;
}
}
var blanket = document.getElementById('blanket');
blanket.style.height = blanket_height + 'px';
var popUpDiv = document.getElementById(popUpDivVar);
popUpDiv_height=blanket_height/2-200;//200 is half popups height
}
function window_pos(popUpDivVar) {
if (typeof window.innerWidth != 'undefined') {
viewportwidth = window.innerHeight;
} else {
viewportwidth = document.documentElement.clientHeight;
}
if ((viewportwidth > document.body.parentNode.scrollWidth) && (viewportwidth > document.body.parentNode.clientWidth)) {
window_width = viewportwidth;
} else {
if (document.body.parentNode.clientWidth > document.body.parentNode.scrollWidth) {
window_width = document.body.parentNode.clientWidth;
} else {
window_width = document.body.parentNode.scrollWidth;
}
}
var popUpDiv = document.getElementById(popUpDivVar);
window_width=window_width/2-300;//300 is half popups width
popUpDiv.style.left = window_width + 'px';
}
function popup(windowname) {
blanket_size(windowname);
window_pos(windowname);
toggle('blanket');
toggle(windowname);
}
</script>
</head>
<body onload="popup('popUpDiv')">
<div id="blanket" style="display:none;"></div>
<div id="popUpDiv" style="display:none;">
<a href="#" onclick="popup('popUpDiv')" >Close</a>
</div>
Click to Open pop-up
</body>
</html>
Actually, I have a piece of code that works, but not along with the above JS and pop-up.
<script type="text/javascript">
function setCookie(name, value, expires, path, domain, secure) {
document.cookie = name + "=" + escape(value) +
((expires) ? "; expires=" + expires : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}
function getCookie(name) {
var cookie = " " + document.cookie;
var search = " " + name + "=";
var setStr = null;
var offset = 0;
var end = 0;
if (cookie.length > 0) {
offset = cookie.indexOf(search);
if (offset != -1) {
offset += search.length;
end = cookie.indexOf(";", offset);
if (end == -1) {
end = cookie.length;
}
setStr = unescape(cookie.substring(offset, end));
}
}
if (setStr == 'false') {
setStr = false;
}
if (setStr == 'true') {
setStr = true;
}
if (setStr == 'null') {
setStr = null;
}
return (setStr);
}
function hidePopup() {
setCookie('popup_state', false);
document.getElementById('popUpDiv').style.display = 'none'; document.getElementById('blanket').style.display = 'none';
}
function showPopup() {
setCookie('popup_state', null);
document.getElementById('popUpDiv').style.display = 'block'; document.getElementById('blanket').style.display = 'block';
}
function checkPopup() {
if (getCookie('popup_state') == null) { // if popup was not closed
document.getElementById('popUpDiv').style.display = 'block'; document.getElementById('blanket').style.display = 'block';
}
}
</script>
I try to execute both scripts such as this:
<body onload="popup('popUpDiv');'checkPopup()';">
I have tried to merge the scripts, but I'm stuck.
Maybe try this:
function popup(windowname) {
if ($.cookie('the_popup') !== '1') {
$.cookie('the_popup', '1', {
expires: 365,
path: '/'
});
//Your code
blanket_size(windowname);
window_pos(windowname);
toggle('blanket');
toggle(windowname);
}
}
This code show your popup only first time.
You need jQuery Cookie plugin