I am trying to make a toggle button on a website that I am making that activates a javascript navbar when pressed then when pressed a second time the navbar retracts out of sight. I have got the code working to where the navbar pops out when the button is pressed but I can't work out how to make the navbar retract.
function tog() {
var x = 0;
if (x == 0) {
document.getElementById("Sidenav").style.height = "450px";
document.getElementById("main").style.marginTop = "0px";
document.body.style.backgroundColor = "rgba(0,0,0,1)";
x = 1;
}
else {
document.getElementById("Sidenav").style.height = "0";
document.getElementById("main").style.marginTop= "0";
document.body.style.backgroundColor = "white";
x = 0;
}
};
This is the javascript that controls the toggle function, and the button is:
<div class="panel"><button class='pan' onclick='tog()'></button></div>
Any input as to where I am going wrong would be much appreciated.
Try this, the logic is: x equals 0 ? then x = 1 else x = 0.
var x = 0;
function tog() {
x = x == 0 ? 1 : 0;
if (x == 0) {
console.log(x)
} else if(x == 1){
console.log(x)
}
};
<div class="panel"><button class='pan' onclick='tog()'>Toggle!</button></div>
You could do something like this.
var x = 0;
function toggle() {
if (x === 0) {
document.getElementById("Sidenav").style.height = "150px";
document.body.style.backgroundColor = "rgba(0,0,0,1)";
x = 1;
} else {
document.getElementById("Sidenav").style.height = "0";
document.body.style.backgroundColor = "white";
x = 0;
}
};
#Sidenav {
width: 400px;
border: 1px solid #9c0000;
border-radius: 10px;
height: 0;
}
<div id="Sidenav"></div>
<button onclick="toggle()">toggle</button>
let sideNav = document.getElementById("Sidenav");
function toggle(){
sideNav.classList.toggle("open");
document.body.classList.toggle("open-bg");
}
.open{
height: 450px;
}
.open-bg{
background-color: rgba(0, 0, 0, 1);
}
make use of toggle method for classList to remove and add class alternately when button is clicked.
and try not to change css attributes too much in JavaScript. I mean it's not bad but it makes your code look kinda big.
Related
I want my code to do the following:
when the right arrow key is pressed, move the circle to the right
when the down arrow key is pressed, move the circle to the bottom
But instead it does the following:
When one of these keys is pressed, it moves only once and than no more. What am I doing wrong?
document.onkeydown = function(event) {
var circle = document.getElementById("circle");
if (event.keyCode == 39) {
circle.style.left += 100;
console.log("right")
} else if (event.keyCode == 40) {
circle.style.top += 100;
console.log("bottom")
}
}
#circle {
width: 50px;
height: 50px;
border-radius: 25px;
background: red;
position: absolute;
}
<div id="circle"></div>
You forgot about the units!
I changed your snippet to keep the actual values in 2 variables and added a function to update the circles style properties by using those vars and appending the units.
<html>
<head>
<title>HTML Test</title>
<style>
#circle {
width: 50px;
height: 50px;
border-radius: 25px;
background: red;
position: absolute;
}
</style>
</head>
<body>
<div id="circle"></div>
</body>
<script>
var circle = document.getElementById("circle");
var circleLeft = 0;
var circleTop = 0;
var updatePosition = function(left, top) {
circle.style.left = left + 'px';
circle.style.top = top + 'px';
};
// once at the start
updatePosition(circleLeft, circleTop);
document.onkeydown = function (event) {
if (event.keyCode == 39) {
circleLeft += 100;
console.log("right");
} else if (event.keyCode == 40) {
circleTop += 100;
console.log("bottom");
}
updatePosition(circleLeft, circleTop);
}
</script>
</html>
There is probably a more elegant way of doing this, but as
Rene said in the comments, you are dealing with strings not numbers and therefore will have trouble actually preforming simple operations like += 100. You instead need to substring the style string, parse the number from it and then add your number, then re-add the "px" to the end (actually might not be necessary since it seems to infer that 100 == 100px in HTML, but not the other way around.)
Here is a fix that worked for moving it left!
<script>
circle.style.left = "0px";
document.onkeydown = function (event) {
var circle = document.getElementById("circle");
if (event.keyCode == 39) {
console.log(circle.style.left.substring(0,circle.style.left.length -2))
circle.style.left = (parseInt(circle.style.left.substring(0,circle.style.left.length -2)) + 100) + "px"
console.log(circle.style.left)
} else if (event.keyCode == 40) {
circle.style.top += 100;
console.log("bottom")
}
}
</script>
Here is the working example. I have set the 10px move position instead of 100px.
Here you can move the circle infinite times as well instead of the single move.
document.onkeydown = function (event) {
var circle = document.getElementById("circle");
if (event.keyCode == 39) {
for (let i = 0; i < 10; i++) {
(i => {
setTimeout(() => {
const left = window.getComputedStyle(circle).left;
circle.style.left = `${(+left.replace("px", "") + i * 2) %
window.innerWidth}px`;
}, 500);
})(i);
}
} else if (event.keyCode == 40) {
for (let j = 0; j < 10; j++) {
(i => {
setTimeout(() => {
const top = window.getComputedStyle(circle).top;
circle.style.top = `${(+top.replace("px", "") + j * 2) %
window.innerWidth}px`;
}, 500);
})(j);
}
}
}
#circle {
width: 50px;
height: 50px;
border-radius: 25px;
background: red;
position: absolute;
}
<div id="circle"></div>
I am trying to make me character moving left and up and I think jump() and slideLeft()
functions are working properly and the problem is in the controller(e) function (else if (e.KeyCode===37)) . The first function is avaible but it isn't able to acces the second conditon function. Also, I would want to make the grid solid after I will make an slideRight() similar function ,so if my character is jumping on it, the platform would sustain the square . Has anyone any ideea for either of my questions ?
Code snippet:
var square = document.querySelector('.square');
var grid = document.querySelector('.grid');
var bottom = 0;
let isJumping = false;
let isGoingLeft = false;
var newBottom;
let left = 0;
let leftTimerId;
function jump() {
if (isJumping) return
let timerUpId = setInterval(function() {
if (bottom > 250) {
clearInterval(timerUpId);
let timerDownId = setInterval(function() {
if (bottom < 0) {
clearInterval(timerDownId);
isJumping = false;
}
bottom -= 5;
square.style.bottom = bottom + 'px';
}, 20)
}
isJumping = true;
bottom += 30;
square.style.bottom = bottom + 'px';
}, 20)
}
function slideLeft() {
console.log('da');
isGoingLeft = true;
leftTimerId = setInterval(function() {
left -= 5;
square.style.left = left + 'px';
}, 20)
}
function controller(e) {
if (e.keyCode === 32)
jump();
else if (e.KeyCode === 37)
slideLeft();
}
document.addEventListener('keydown', controller);
.grid {
position: absolute;
background-color: chartreuse;
height: 20px;
width: 500px;
bottom: 100px;
left: 100px;
}
.square {
position: absolute;
background-color: darkblue;
height: 100px;
width: 100px;
bottom: 0px;
left: 150px;
}
`
<div class="grid"></div>
<div class="square"></div>
EDIT:
There is a typo:
The second time you've written KeyCode
function controller(e) {
if(e.keyCode===32) {
jump();
}
else if(e.keyCode===37) {
slideLeft();
}
}
I don't really understand what you mean by the second part of your question. If you want a character to have the ability to jump on a square, you'll have to implement a collision detection. Something like this:
if ( isNotOnGround() ) {
fall()
}
I have made 30 buttons in JavaScript now I want all buttons to be green like the first button and whenever you click on a button it turns and stays red.
For some reason only the first button is green and whenever I click it it won't turn red. I tried using: button.style.backgroundColor = "red"; in a function to make the button red when clicked but this doesn't work
const color = ["green"];
page();
function onbuttonclicked() {
document.body.style.backgroundColor = color[nr - 1];
}
function page() {
document.body.style.backgroundColor = "grey";
//style page
createButtons(30);
}
function set_onclick(amount) {
for (var a = 1; a < (amount + 1); a++) {
document.getElementById("button" + a).setAttribute("onclick", "onbuttonclicked(" + a + ")");
}
}
function createButtons(amount) {
for (var a = 1; a < (amount + 1); a++) {
var button = document.createElement("button");
button.style.backgroundColor = color[a - 1];
button.id = "button" + a;
button.innerHTML = "button " + a;
container.appendChild(button);
}
set_onclick(amount);
}
<div id="container"></div>
EDIT
thanks for all the answers it isnt possible to only change certain buttons when you click on them right? so when i click on button1 nothing happens but whenever i click on button 3 it turn red
You need to pass nr as a parameter in onbuttonclicked function
EDIT:
OP Comment:
okay so i need to add an parameter. but i want all 30 buttons to be green so when you open the page all buttons are green this also has to do with the parameter?
For that in your loop createButton, change color[a - 1] for color[0]
const color = ["green"];
function onbuttonclicked(nr) {
document.body.style.backgroundColor = color[nr - 1];
}
function page() {
//style page
document.body.style.backgroundColor = "grey";
createButtons(30);
}
function set_onclick(amount, nr) {
for (let a = 1; a < (amount + 1); a++) {
document.getElementById(`button${a}`).setAttribute("onclick", `onbuttonclicked(${nr})`);
}
}
function createButtons(amount) {
for (let a = 1; a < (amount + 1); a++) {
const button = document.createElement("button");
button.style.backgroundColor = color[0];
button.id = `button${a}`;
button.innerHTML = `button ${a}`;
container.appendChild(button);
}
set_onclick(amount, 1);
}
page();
<div id="container"></div>
const number_of_buttons = 30;
createButtons();
function createButtons(){
var container = document.getElementById("container");
for(var i=1;i<=number_of_buttons;i++){
var button = document.createElement("button");
button.innerText = "Button " + i;
button.style.backgroundColor = "green";
button.onclick = function(event){
var source = event.target || event.srcElementl
source.style.backgroundColor = "red";
};
container.appendChild(button);
}
}
button{
margin: 10px;
font-family: 'Consolas';
font-size: 20px;
padding: 5px;
outline: none;
cursor: pointer;
transition: 0.5s;
}
button:hover{
border: 1px solid black;
}
button:active{
transform: translateY(2px);
}
<div id="container">
</div>
This is what you have asked for!
I did the styling for better looks!
This line: button.style.backgroundColor = color[a - 1]; is wrong, since your color array only contains a single string ("green"). You should do color[0], or, you need to populate the array to have 30 elements.
document.body.style.backgroundColor = color[nr - 1]; - Where is this nr variable came from? The correct line should be button.style.backgroundColor = "red"; or - again - you can populate the color (i.e const color=["green", "red"]) and use color[1].
Check out this demo
A common way to do this is to use CSS classes:
page();
function onbuttonclicked(a) {
//document.body.style.backgroundColor = color[nr - 1];
document.getElementById("button" + a).classList.remove("button")
document.getElementById("button" + a).classList.add("clickedbutton")
}
function set_onclick(amount) {
for (var a = 1; a < (amount + 1); a++) {
document.getElementById("button" + a).setAttribute("onclick", "onbuttonclicked(" + a + ")");
}
}
function page() {
document.body.style.backgroundColor = "grey";
//style page
createButtons(30);
}
function createButtons(amount){
for (var a = 1;a <(amount + 1); a++) {
var button = document.createElement("button");
button.classList.add("button")
button.id = "button" + a;
button.innerHTML = "button " + a;
container.appendChild(button);
}
set_onclick(amount);
}
.clickedbutton {
background-color: red;
}
.button {
background-color: green;
}
<div id="container"></div>
I'm working on a Slider Puzzle and stumbled on a question. I have been trying to make my reset function to stop counting moves on the page when it is pressed but had no luck. My start function starts the counter and ends when the game ends, so how would my counter end counting but still keep the number of moves on display before the user had pressed the reset button?
var gamePiece;
var notify;
var timer;
var spaceY;
var spaceX;
var ticker;
var totalMoves;
function initialize() {
var puzzleArea = document.getElementById("puzzlearea");
gamePiece = puzzleArea.getElementsByTagName("div"); //retrieve element within puzzlearea
for (var i = 0; i < gamePiece.length; i++) //applies features to each puzzle piece
{
gamePiece[i].className = "puzzlepiece"; //setting up the puzzle piece code
gamePiece[i].style.left = (i % 4 * 100) + "px"; //calculates the position for puzzle pieces from the left of the screen
gamePiece[i].style.top = (parseInt(i / 4) * 100) + "px"; //calculates the position for puzzle pieces from the top of the screen
gamePiece[i].onmouseover = function () //applies features when mouse moves over puzzle pieces
{
if (checkMove(parseInt(this.innerHTML))) //checks whenever a move is made
{
this.style.border = "3px solid red"; //changes to red when a puzzle piece is near an empty space
this.style.color = "#006600"; //text color changes to green when a puzzle piece is near an empty space
this.style.textDecoration = "underline"; //underlines the number of the puzzle piece piece
//console.log(totalMoves);
}
}
gamePiece[i].onmouseout = function () //activates whenever mouse moves out of puzzle piece
{
this.style.border = "2px solid black"; //reverts to its original size border
this.style.color = "#000000"; //reverts to original text color
this.style.textDecoration = "none"; //reverts to original text state
}
gamePiece[i].onclick = function () //activates when mouse clicks on a puzzle piece
{
if (checkMove(parseInt(this.innerHTML))) //checks whether or not the puzzle piece can move into an empty space
{
swap(this.innerHTML - 1); //moves into an empty space if true
totalMoves++;
display();
if (finish()) //checks when the all the 15 pieces are in its right space
{
win(); //alerts the player that they have won the game
}
return;
}
}
}
}
spaceX = '300px';
spaceY = '300px';
function checkMove(position) // returns true whenever a piece can be moved into an empty space
{
if (left(spaceX, spaceY) == (position - 1))
{
// totalMoves++;
return true;
}
if (down(spaceX, spaceY) == (position - 1))
{
// totalMoves++;
return true;
}
if (up(spaceX, spaceY) == (position - 1))
{
//totalMoves++;
return true;
}
if (right(spaceX, spaceY) == (position - 1))
{
//totalMoves++;
return true;
}
}
function Notify() //notifies the user
{
notify--; //decrements the value of
if (notify == 0) //if the value reaches the end then
{
var body = document.getElementsByTagName("body"); //retrieves body element in html
body[0].style.backgroundImage = "none"; //reverts to original page background
alert("Winner! ... Press Start and Play Again"); //tells the user that they have won the game
location.href = "15 Slider Puzzle.html"
return;
} else(notify % 2)
{
var body = document.getElementsByTagName("body");
}
timer = setTimeout(Notify, 100); //notifies the user for 1 secs
}
function win() //notifies user that they have won
{
var body = document.getElementsByTagName("body");
notify = 10; //initializes notify variable
timer = setTimeout(Notify, 10);
}
function finish() //checks when the game reaches its end
{
var flag = true;
for (var i = 0; i < gamePiece.length; i++) //for each puzzle piece
{
var top = parseInt(gamePiece[i].style.top);
var left = parseInt(gamePiece[i].style.left);
if (left != (i % 4 * 100) || top != parseInt(i / 4) * 100) //checks if each piece matches its left and top position
{
flag = false;
break; //breaks the loop
}
}
return flag;
}
function left(x, y) //calculates how far to the left a puzzlepiece should position
{
var cordX = parseInt(x);
var cordY = parseInt(y);
if (cordX > 0)
{
for (var i = 0; i < gamePiece.length; i++)
{
if (parseInt(gamePiece[i].style.left) + 100 == cordX && parseInt(gamePiece[i].style.top) == cordY)
{
return i;
}
}
} else
{
return -1;
}
}
function right(x, y) //calculates how far to the right a puzzlepiece should position
{
var cordX = parseInt(x);
var cordY = parseInt(y);
if (cordX < 300)
{
for (var i = 0; i < gamePiece.length; i++) {
if (parseInt(gamePiece[i].style.left) - 100 == cordX && parseInt(gamePiece[i].style.top) == cordY)
{
return i;
}
}
} else
{
return -1;
}
}
function up(x, y) //calculates how far up a puzzlepiece should position
{
var cordX = parseInt(x);
var cordY = parseInt(y);
if (cordY > 0)
{
for (var i = 0; i < gamePiece.length; i++)
{
if (parseInt(gamePiece[i].style.top) + 100 == cordY && parseInt(gamePiece[i].style.left) == cordX)
{
return i;
}
}
} else
{
return -1;
}
}
function down(x, y) //calculates how far down a puzzlepiece should position
{
var cordX = parseInt(x);
var cordY = parseInt(y);
if (cordY < 300)
{
for (var i = 0; i < gamePiece.length; i++)
{
if (parseInt(gamePiece[i].style.top) - 100 == cordY && parseInt(gamePiece[i].style.left) == cordX)
{
return i;
}
}
} else
{
return -1;
}
}
function swap(position) //moves the puzzle piece by switching position with an empty space
{
var temp = gamePiece[position].style.top;
gamePiece[position].style.top = spaceY;
spaceY = temp;
temp = gamePiece[position].style.left;
gamePiece[position].style.left = spaceX;
spaceX = temp;
}
function start() //starts the move counter when the button is pressed
{
totalMoves = 0;
ticker = document.getElementById("Moves");
}
function display() //helps update the display when a move is successfully made
{
ticker.innerHTML = totalMoves;
}
function reset()
{
}
body {
background-color: white;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 14px;
}
#controls,
#overall,
#puzzlearea {
width: 400px;
}
#controls {
padding-top: 10px;
text-align: center;
}
h1 {
margin: 10px 0px;
text-align: center;
}
/* Used to center the puzzle. */
#overall {
margin-left: auto;
margin-right: auto;
}
/* The area that holds the 15 puzzle pieces. */
#puzzlearea {
font-size: 32px;
height: 400px;
padding: 0px;
position: relative;
}
/* This class should be applied to each of the 15 puzzle pieces. */
.puzzlepiece {
border: 2px solid black;
height: 96px;
line-height: 96px;
position: absolute;
text-align: center;
vertical-align: middle;
width: 96px;
}
/* This class should be applied to a puzzle piece that can be moved. */
.movablepiece:hover {
border-color: red;
color: #006600;
text-decoration: underline;
}
<!DOCTYPE HTML>
<html>
<title> 15 Slider Puzzle</title>
<link rel="stylesheet" type="text/css" href="15 Slider.css" />
<script src="15 Slider.js" type="text/javascript"></script>
<head>
<body onload = "initialize()">
<h1>Slider Puzzle</h1>
<div id="overall">
<div id="puzzlearea">
<!-- the following are the fifteen puzzle pieces -->
<div>1</div> <div>2</div> <div>3</div> <div>4</div>
<div>5</div> <div>6</div> <div>7</div> <div>8</div>
<div>9</div> <div>10</div> <div>11</div> <div>12</div>
<div>13</div> <div>14</div> <div>15</div>
</div>
<div id="controls"></div>
<button onclick = "start();">Start</button>
<button onclick = "reset();">Reset</button>
<br>
Number Of Moves: <span id="Moves">0</span>
</div><!--content-->
<br>
</head>
</html>
I have added a var hasStopped which will only add moves if its false and if reset is clicked it will set to true which means the swap will still run but moves will not counted as well.
Also, when you clicked start() again the totalMoves will start counting the moves again. If you want that too.
Here is working demo for you: https://jsfiddle.net/usmanmunir/cs4d3qfm/16/
var gamePiece;
var notify;
var timer;
var spaceY;
var spaceX;
var ticker;
var totalMoves;
var hasStopped = false;
function initialize() {
var puzzleArea = document.getElementById("puzzlearea");
gamePiece = puzzleArea.getElementsByTagName("div"); //retrieve element within puzzlearea
for (var i = 0; i < gamePiece.length; i++) //applies features to each puzzle piece
{
gamePiece[i].className = "puzzlepiece"; //setting up the puzzle piece code
gamePiece[i].style.left = (i % 4 * 100) + "px"; //calculates the position for puzzle pieces from the left of the screen
gamePiece[i].style.top = (parseInt(i / 4) * 100) + "px"; //calculates the position for puzzle pieces from the top of the screen
gamePiece[i].onmouseover = function() //applies features when mouse moves over puzzle pieces
{
if (checkMove(parseInt(this.innerHTML))) //checks whenever a move is made
{
this.style.border = "3px solid red"; //changes to red when a puzzle piece is near an empty space
this.style.color = "#006600"; //text color changes to green when a puzzle piece is near an empty space
this.style.textDecoration = "underline"; //underlines the number of the puzzle piece piece
//console.log(totalMoves);
}
}
gamePiece[i].onmouseout = function() //activates whenever mouse moves out of puzzle piece
{
this.style.border = "2px solid black"; //reverts to its original size border
this.style.color = "#000000"; //reverts to original text color
this.style.textDecoration = "none"; //reverts to original text state
}
gamePiece[i].onclick = function() //activates when mouse clicks on a puzzle piece
{
if (checkMove(parseInt(this.innerHTML))) //checks whether or not the puzzle piece can move into an empty space
{
swap(this.innerHTML - 1); //moves into an empty space if true
if (!hasStopped) {
totalMoves++;
display();
}
if (finish()) //checks when the all the 15 pieces are in its right space
{
win(); //alerts the player that they have won the game
}
return;
}
}
}
}
spaceX = '300px';
spaceY = '300px';
function checkMove(position) // returns true whenever a piece can be moved into an empty space
{
if (left(spaceX, spaceY) == (position - 1))
{
// totalMoves++;
return true;
}
if (down(spaceX, spaceY) == (position - 1))
{
// totalMoves++;
return true;
}
if (up(spaceX, spaceY) == (position - 1))
{
//totalMoves++;
return true;
}
if (right(spaceX, spaceY) == (position - 1))
{
//totalMoves++;
return true;
}
}
function Notify() //notifies the user
{
notify--; //decrements the value of
if (notify == 0) //if the value reaches the end then
{
var body = document.getElementsByTagName("body"); //retrieves body element in html
body[0].style.backgroundImage = "none"; //reverts to original page background
alert("Winner! ... Press Start and Play Again"); //tells the user that they have won the game
location.href = "15 Slider Puzzle.html"
return;
} else(notify % 2)
{
var body = document.getElementsByTagName("body");
}
timer = setTimeout(Notify, 100); //notifies the user for 1 secs
}
function win() //notifies user that they have won
{
var body = document.getElementsByTagName("body");
notify = 10; //initializes notify variable
timer = setTimeout(Notify, 10);
}
function finish() //checks when the game reaches its end
{
var flag = true;
for (var i = 0; i < gamePiece.length; i++) //for each puzzle piece
{
var top = parseInt(gamePiece[i].style.top);
var left = parseInt(gamePiece[i].style.left);
if (left != (i % 4 * 100) || top != parseInt(i / 4) * 100) //checks if each piece matches its left and top position
{
flag = false;
break; //breaks the loop
}
}
return flag;
}
function left(x, y) //calculates how far to the left a puzzlepiece should position
{
var cordX = parseInt(x);
var cordY = parseInt(y);
if (cordX > 0)
{
for (var i = 0; i < gamePiece.length; i++)
{
if (parseInt(gamePiece[i].style.left) + 100 == cordX && parseInt(gamePiece[i].style.top) == cordY)
{
return i;
}
}
} else
{
return -1;
}
}
function right(x, y) //calculates how far to the right a puzzlepiece should position
{
var cordX = parseInt(x);
var cordY = parseInt(y);
if (cordX < 300)
{
for (var i = 0; i < gamePiece.length; i++) {
if (parseInt(gamePiece[i].style.left) - 100 == cordX && parseInt(gamePiece[i].style.top) == cordY)
{
return i;
}
}
} else
{
return -1;
}
}
function up(x, y) //calculates how far up a puzzlepiece should position
{
var cordX = parseInt(x);
var cordY = parseInt(y);
if (cordY > 0)
{
for (var i = 0; i < gamePiece.length; i++)
{
if (parseInt(gamePiece[i].style.top) + 100 == cordY && parseInt(gamePiece[i].style.left) == cordX)
{
return i;
}
}
} else
{
return -1;
}
}
function down(x, y) //calculates how far down a puzzlepiece should position
{
var cordX = parseInt(x);
var cordY = parseInt(y);
if (cordY < 300)
{
for (var i = 0; i < gamePiece.length; i++)
{
if (parseInt(gamePiece[i].style.top) - 100 == cordY && parseInt(gamePiece[i].style.left) == cordX)
{
return i;
}
}
} else
{
return -1;
}
}
function swap(position) //moves the puzzle piece by switching position with an empty space
{
var temp = gamePiece[position].style.top;
gamePiece[position].style.top = spaceY;
spaceY = temp;
temp = gamePiece[position].style.left;
gamePiece[position].style.left = spaceX;
spaceX = temp;
}
function start() //starts the move counter when the button is pressed
{
totalMoves = 0;
hasStopped = false
ticker = document.getElementById("Moves");
}
function display() //helps update the display when a move is successfully made
{
ticker.innerHTML = totalMoves;
}
function reset() {
hasStopped = true
}
body {
background-color: white;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 14px;
}
#controls,
#overall,
#puzzlearea {
width: 400px;
}
#controls {
padding-top: 10px;
text-align: center;
}
h1 {
margin: 10px 0px;
text-align: center;
}
/* Used to center the puzzle. */
#overall {
margin-left: auto;
margin-right: auto;
}
/* The area that holds the 15 puzzle pieces. */
#puzzlearea {
font-size: 32px;
height: 400px;
padding: 0px;
position: relative;
}
/* This class should be applied to each of the 15 puzzle pieces. */
.puzzlepiece {
border: 2px solid black;
height: 96px;
line-height: 96px;
position: absolute;
text-align: center;
vertical-align: middle;
width: 96px;
}
/* This class should be applied to a puzzle piece that can be moved. */
.movablepiece:hover {
border-color: red;
color: #006600;
text-decoration: underline;
}
<!DOCTYPE HTML>
<html>
<title> 15 Slider Puzzle</title>
<link rel="stylesheet" type="text/css" href="15 Slider.css" />
<script src="15 Slider.js" type="text/javascript"></script>
<head>
<body onload="initialize()">
<h1>Slider Puzzle</h1>
<div id="overall">
<div id="puzzlearea">
<!-- the following are the fifteen puzzle pieces -->
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
<div>10</div>
<div>11</div>
<div>12</div>
<div>13</div>
<div>14</div>
<div>15</div>
</div>
<div id="controls"></div>
<button onclick="start();">Start</button>
<button onclick="reset();">Reset</button>
<br> Number Of Moves: <span id="Moves">0</span>
</div>
<!--content-->
<br>
</head>
</html>
Use this as a demo https://jsfiddle.net/ugonnaezema/0gpeo1sj/2/
Initialize a new variable to check if the reset button has been pressed
var isResetPressed = false;
Set isResetPressed to false when initialize is called, then check if the reset button is pressed
function initialize() {
var puzzleArea = document.getElementById("puzzlearea");
gamePiece = puzzleArea.getElementsByTagName("div"); //retrieve element within puzzlearea
isResetPressed = false;
for (var i = 0; i < gamePiece.length; i++) //applies features to each puzzle piece
{
...
gamePiece[i].onclick = function () //activates when mouse clicks on a puzzle piece
{
if (checkMove(parseInt(this.innerHTML))) //checks whether or not the puzzle piece can move into an empty space
{
swap(this.innerHTML - 1); //moves into an empty space if true
if (isResetPressed)
{
totalMoves = totalMoves;
}
else
{
totalMoves++;
}
display();
if (finish()) //checks when the all the 15 pieces are in its right space
{
win(); //alerts the player that they have won the game
}
return;
}
}
...
Set up the reset function as follows
function reset()
{
display();
isResetPressed = true;
}
Ok, in your reset function, pop the current moves into a temp variable and display that, then totalMovves = 0;
You could either manually change the display to use the old value:
ticker.innerHTML = totalMoves;
totalMoves = 0;
But I would do this by altering the Display function to look like below:
function display(var moves = totalMoves) //helps update the display when a move is successfully made
{
ticker.innerHTML = moves;
}
Or you could simply change the order of your commands
function reset(){
display();
totalMoves = 0;
}
Having an issue with changing classes. I can get it to work if I hardcode pixels into the style change but wanted a cleaner version using classes and CSS. The goal is to have the pixel change sizes larger and smaller due to the value of healthPercent in width. This part works but the trouble part is changing the classes to change the color of the bar. For some reason, it does not pass through the if statements correctly and just stays green until death (zero or less for healthPercent), when it reaches zero and then turns red. I can't quite figure out why it passes through the first if check but not the rest. Any ideas on how to fix this?
EDIT: I'm working on a game. just to clarify.
JAVASCRIPT
displayLifeBar = function ()
{
pixelMod = 2.3; //added definition here but global on full code
healthPercent = 130; //added here for example but passed down
lifeBar = 'player_lifebar';
document.getElementById(lifeBar).style.width = healthPercent + 'px';
var criticalLife = 25 * pixelMod;
var lowLife = 50 * pixelMod;
var hurtLife = 75 * pixelMod;
if (healthPercent <= 0){
document.getElementById(lifeBar).className = '';
}
else if (healthPercent < criticalLife){
document.getElementById(lifeBar).className = 'lifebar critical';
}
else if (healthPercent < lowLife){
document.getElementById(lifeBar).className = 'lifebar low';
}
else if (healthPercent < hurtLife){
document.getElementById(lifeBar).className = 'lifebar hurt';
}
else
{
document.getElementById(lifeBar).className = 'lifebar';
}
}
CSS
/* LIFEBAR COLORS STARTS */
.lifebar{
height:20px;
background-color: forestgreen;
}
.lifebar.hurt{
background-color: gold;
}
.lifebar.low{
background-color: orange;
}
.lifebar.critical{
background-color: red;
}
/* LIFEBAR COLORS ENDS */
Your code snippet seems to be working from what you described - assuming your HTML just looks like <div id='player_lifebar'></div>.
var pixelMod = 2.3;
var healthPercent = 10;
var lifeBar = 'player_lifebar';
displayLifeBar = function ()
{
document.getElementById(lifeBar).style.width = healthPercent + 'px';
var criticalLife = 25 * pixelMod;
var lowLife = 50 * pixelMod;
var hurtLife = 75 * pixelMod;
if (healthPercent <= 0){
document.getElementById(lifeBar).className = '';
} else if (healthPercent < criticalLife){
document.getElementById(lifeBar).className = 'lifebar critical';
} else if (healthPercent < lowLife){
document.getElementById(lifeBar).className = 'lifebar low';
} else if (healthPercent < hurtLife){
document.getElementById(lifeBar).className = 'lifebar hurt';
} else {
document.getElementById(lifeBar).className = 'lifebar';
}
}
displayLifeBar();
// for testing:
function modifyHealth(points) {
healthPercent = healthPercent + points;
displayLifeBar(); //re-render healthbar
}
document.getElementById('heal').addEventListener('click', function() { modifyHealth(10) });
document.getElementById('attack').addEventListener('click', function() { modifyHealth(-10) });
.lifebar{
height:20px;
background-color: forestgreen;
}
.lifebar.hurt{
background-color: gold;
}
.lifebar.low{
background-color: orange;
}
.lifebar.critical{
background-color: red;
}
<div id='player_lifebar'></div>
<!-- for testing -->
<br>
<button id='heal'>♡ heal (+10)</button>
<button id='attack'>🗡 attack (-10)</button>