Creating health bar that increases in value based on users level - javascript

Hello I am trying to create a healthbar that scales in max value based on the users level.
But I am kinda stuck with it because everytime the healthbar ends up in not having the right length based on the users level and it's health. The system works like this: the user starts at level 1 with a health value of 150 and increases + 10 everytime the user levels up, the max level that exists is 32.
Now I know this might be possible to do with a loop but I am not sure on how do this correctly:
This is the code for the health bar. The user_level is the users level and I am trying to change the element style based on his health, but at the same time that it would match with the current level of the user.
for (let i = 0; i < user_level.value; i++) {
playerhealthbar.style.width = user_health // Something here but I dont know how to.
}
This is the CSS code if it helps. What happens is that the greenbar should shrink so that the red bar underneath becomes visible.
#playerhealth {
position: absolute;
bottom: 0;
left: 0;
height: 45px;
width: 325px;
background: lightgreen;
}
#playerhealthbar {
position: absolute;
height: 50px;
width: 330px;
border: rgb(255, 255, 255) 3px solid;
border-radius: 3px;
margin-right: 20px;
display: inline-block;
margin-top: 442px;
margin-left: 70px;
background: rgb(158, 31, 31);
}
#playerhealthvalue{
position: absolute;
margin-top: 500px;
margin-left: 220px;
font-size: 30px;
color: black;
}

The complete outerbar stays the same. But the greenbar thats inside the whole frame shrinks in size when the health goes down.
So the first thing you have to calculate is what the current maximum health value is. This is given by currentMaxHealth = 150 + 10 * (level-1).
The percent of the green bar is playerHealth / currentMaxHealth * 100.
The whole logic can be done with just custom properties calc and var.
So the CSS could look like this:
function setCurrentHealth(val) {
let root = document.documentElement;
root.style.setProperty('--curr-health', val);
}
function setUserLevel(level) {
let root = document.documentElement;
root.style.setProperty('--user-level', level);
}
document.querySelector('#level').addEventListener('input', (evt) => {
setUserLevel(evt.target.value)
})
document.querySelector('#health').addEventListener('input', (evt) => {
setCurrentHealth(evt.target.value)
})
:root {
--user-level: 1;
--curr-health: 10;
--base-health-level: 150;
--additional-health-per-level: 10;
}
.current-health {
width: calc(var(--curr-health) / (var(--base-health-level) + var(--additional-health-per-level) * (var(--user-level) - 1)) * 100%);
height: 100%;
background-color: green;
}
.health-bar {
border: 1px solid black;
width: 300px;
height: 20px;
}
<div class="health-bar">
<div class="current-health">
</div>
</div>
Level: <input value="1" id="level"><br>
Health: <input value="10" id="health">

Related

"Progress" bar with both value and acceptable ranges

Here is exhaustive topic on SO about how to create progress bar. I would like to improve this "widget" to display acceptable range markers. It may be vertical lines or something else.
For example, value range may be [-50;50], but acceptable range is [-25;25]. So can someone point me out how to modify, for example, the first answer from topic mentioned above to get what I described here.
Here is first suggested answer from the topic:
#progressbar {
background-color: black;
border-radius: 13px;
/* (height of inner div) / 2 + padding */
padding: 3px;
}
#progressbar>div {
background-color: orange;
width: 40%;
/* Adjust with JavaScript */
height: 20px;
border-radius: 10px;
}
<div id="progressbar">
<div></div>
</div>
Here is how I see my widget. Red parts of bar - acceptable range.
Clarification
So firstly, as mentioned in my comment, this doesn't really sound like a progress bar. As implied by the name, progress bars are meant to show progress, and so things like negative values don't make sense.
It sounds like you want something like the HTML Range Input, though you mentioned you only want to display data (which you could still technically do by setting the disabled attribute on a range input).
Possible Solution
Ultimately it looks like you just want CSS to display a range (not a progress bar). This can be achieved with pure CSS, but I should mention there are a few quirks based on the requirements you have outlined.
You could set all the values by hand, based on whatever range and value you wish to display, but I assume this isn't desirable. So the next thing to do would be to utilize CSS variables and the CSS calc() function to set everything for you (based on some initial data).
The one weird thing is displaying the text for things like the range and values. Because we are using CSS variables to hold our values and perform calculations, it would be nice to use those same values to display the text. But CSS variables cannot be converted between types and so a value of say 2 is a number (not text or a string), and this means the value of 2 cannot be displayed as text using the CSS content property. Because of this I have 2 sets of variables. The first set is the number, used for calculations to set the widths. The second set is the -text version, used to display the text under your range bar.
.rangeBar {
background: #EEE;
height: 2em;
padding: .2em;
border: 1px solid #CCC;
border-radius: 1em;
box-sizing: border-box;
position: relative;
--min-value: 0;
--min-value-text: '0';
--max-value: 4.5;
--max-value-text: '4.5';
--min-range: 1;
--min-range-text: '1';
--max-range: 3;
--max-range-text: '3';
--value: 2;
--value-text: '2';
}
.rangeBar::before {
content: var(--min-value-text);
position: absolute;
top: 100%;
left: 0;
color: #888;
}
.rangeBar::after {
content: var(--max-value-text);
position: absolute;
top: 100%;
right: 0;
color: #888;
}
.rangeBar .value {
background: #0A95FF;
width: calc(var(--value)/var(--max-value)*100%);
height: 100%;
border-radius: 1em;
position: relative;
z-index: 1;
}
.rangeBar .value::after {
content: var(--value-text);
position: absolute;
top: 100%;
right: 0;
color: #888;
}
.rangeBar .minRange {
background: #E74C3C;
width: calc(var(--min-range)/var(--max-value)*100%);
height: 100%;
border-radius: 1em;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
position: absolute;
top: 0;
left: 0;
z-index: 2;
}
.rangeBar .minRange::after {
content: var(--min-range-text);
position: absolute;
top: 100%;
right: 0;
color: #888;
}
.rangeBar .maxRange {
background: #E74C3C;
width: calc((var(--max-value) - var(--max-range))/var(--max-value)*100%);
height: 100%;
border-radius: 1em;
border-top-left-radius: 0;
border-bottom-left-radius: 0;
position: absolute;
top: 0;
right: 0;
z-index: 2;
}
.rangeBar .maxRange::after {
content: var(--max-range-text);
position: absolute;
top: 100%;
left: 0;
color: #888;
}
<div class="rangeBar">
<div class="minRange"></div>
<div class="value"></div>
<div class="maxRange"></div>
</div>
Additional Notes
There are possibly a few ways to simplify the CSS for this and automatically take care of some of the issues with this, but would require JavaScript (which is outside of the scope of this question). There has been no indication as to how any of the data or values for this range bar will be set, and so JavaScript was avoided for this question.
EDIT
Because OP updated the original question to include JavaScript, I am adding an additional solution. This mostly works the same but instead uses a JavaScript function called _CreateRange that takes 5 parameters (min value, max value, min range, max range, and value) and creates a new element on the page that uses those parameters/values. This makes things a little simpler as you only need to enter those values once (rather than once for the number value and once for the text value) and you can also use this to dynamically create or load ranges on the page (depending on where the data for these ranges is coming from).
// These are just example values you can modify
let value = 2,
minValue = 0,
maxValue = 4.5,
minRange = 1,
maxRange = 3;
const _CreateRange = (mnV, mxV, mnR, mxR, v) => {
let r = document.createElement("div");
r.className = "rangeBar";
r.innerHTML = `<div class="minRange"></div><div class="value"></div><div class="maxRange"></div>`;
r.style.setProperty("--min-value", mnV);
r.style.setProperty("--min-value-text", JSON.stringify(mnV+""));
r.style.setProperty("--max-value", mxV);
r.style.setProperty("--max-value-text", JSON.stringify(mxV+""));
r.style.setProperty("--min-range", mnR);
r.style.setProperty("--min-range-text", JSON.stringify(mnR+""));
r.style.setProperty("--max-range", mxR);
r.style.setProperty("--max-range-text", JSON.stringify(mxR+""));
r.style.setProperty("--value", v);
r.style.setProperty("--value-text", JSON.stringify(v+""));
document.querySelector("#bar").append(r);
}
// This is where the function to create the range is called
// We are using our default example values from earlier, but you can pass in any values
_CreateRange(minValue, maxValue, minRange, maxRange, value);
.rangeBar {
background: #EEE;
height: 2em;
padding: .2em;
border: 1px solid #CCC;
box-sizing: border-box;
position: relative;
margin: 0 0 2em;
}
.rangeBar::before {
content: var(--min-value-text);
position: absolute;
top: 100%;
left: 0;
color: #888;
}
.rangeBar::after {
content: var(--max-value-text);
position: absolute;
top: 100%;
right: 0;
color: #888;
}
.rangeBar .value {
background: #0A95FF;
width: calc(var(--value)/var(--max-value)*100%);
height: 100%;
position: relative;
z-index: 1;
}
.rangeBar .value::after {
content: var(--value-text);
position: absolute;
top: 100%;
right: 0;
color: #888;
margin: .2em 0 0;
}
.rangeBar .minRange {
background: #E74C3C;
width: calc(var(--min-range)/var(--max-value)*100%);
height: 100%;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
position: absolute;
top: 0;
left: 0;
z-index: 2;
}
.rangeBar .minRange::after {
content: var(--min-range-text);
position: absolute;
top: 100%;
right: 0;
color: #888;
}
.rangeBar .maxRange {
background: #E74C3C;
width: calc((var(--max-value) - var(--max-range))/var(--max-value)*100%);
height: 100%;
border-top-left-radius: 0;
border-bottom-left-radius: 0;
position: absolute;
top: 0;
right: 0;
z-index: 2;
}
.rangeBar .maxRange::after {
content: var(--max-range-text);
position: absolute;
top: 100%;
left: 0;
color: #888;
}
<div id="bar"></div>

How can a span id that div classes are applied to be looped?

I'm new to coding, and I'm trying to learn the basics. I wanted to practice what I learned by making flashcards (nothing complicated like saving it, importing it, or exporting it). So far, I made a table that the user can edit. I know how to gather data from the table, but I don't know how to make a CSS flashcard appear every time the user adds a card to the table. I am aware that the code will not work since I put the CSS in JavaScript since this code is just meant to show what I am trying to do. Also, if I am taking a completely wrong approach, please let me know. Thank you! Please excuse the poor variable naming, I was just testing some things.
<script>
function getFlashcardValue() {
for (var repeat = 0; repeat < 200; repeat++) {
var Table = document.getElementById('flashcardsTable');
var column1 = 0;
var column2 = 1;
var numberOfFlashcards = 2;
for (var row = 0; row < numberOfFlashcards; row++) {
var Cells = Table.rows.item(1).cells;
var Question1 = Cells.item(column1).innerHTML;
var Cells1 = Table.rows.item(1).cells;
var Answer1 = Cells.item(column2).innerHTML;
document.getElementById("myFlashcardQuestion" + row).innerHTML = Question1;
document.getElementById("myFlashcardAnswer" + row).innerHTML = Answer1;
<div class="flip-card">
<div class="flip-card-inner">
<div class="flip-card-front">
<span id="myFlashcardQuestion1"></span>
</div>
<div class="flip-card-back">
<span id="myFlashcardAnswer1"></span>
</div>
</div>
</div>
}
}
}
</script>
<p style = "font-size: 25px">Hover over the flashcard to flip it!</p>
<style>
.flip-card {
background-color: transparent;
width: 350px;
height: 175px;
margin: auto;
padding: 5px 5px;
perspective: 1000px;
}
.flip-card-inner {
position: relative;
background-color: lightblue;
width: 100%;
height: 100%;
text-align: center;
transition: transform 0.6s;
transform-style: preserve-3d;
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
}
.flip-card:hover .flip-card-inner {
transform: rotateY(180deg);
}
.flip-card-front, .flip-card-back {
position: absolute;
width: 100%;
height: 100%;
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
}
.flip-card-front {
background-color: lightblue;
width: 350px;
height: 175px;
color: black;
font-size: 35px;
text-alignment: center;
}
.flip-card-back {
background-color: red;
color: white;
font-size: 35px;
text-alignment: center;
transform: rotateY(180deg);
}
</style>
So first of all you can create a code snippet in stackoverflows editor (see below), or use jsfiddle and post a shared-link.
It depends on which action the user has to do after he enters the data.
If it is, for example, a button click, then it is possible to call a function that shows the user's input in the flashcard. Now if you want that for every single Q&A you have to create Elements in the for loop and edit them there. Here a little example.
var allCards = document.getElementById("allCards");
for (var i = 1; i <= 5; i++) { //i used 5, you should use length of data
var question = document.createElement("div");
question.textContent = "Question " + i;
question.classList.add("flip-card");
allCards.appendChild(question);
}
.flip-card {
background-color: lightblue;
width: 350px;
height: 175px;
margin: 10px auto;
padding: 5px 5px;
font-size: 35px;
text-align: center;
}
<div id="allCards"></div>
Edit:
As promised, here is an example of how you can set up the flip cards.
https://jsfiddle.net/ybu59hfp/1/
Your concern should now be resolved. If you have any further questions, feel free to write to me in the chat or read a little about JavaScript on the Internet.

var in style.setProperty does not render

I have a progress bar which increases based on numbers entered by the user:
<div class="progressBarContainer percentBar">
<div class="progressBarPercent" style="--width:${gPercent}" id="${gName}-pbar"></div>
</div>
I use a variable in the style to define the width of the progress bar
.progressBarPercent {
background-color: var(--progressbar-main-color);
width: calc(var(--width, 0) * 1%); <== THIS
min-width: 10px;
max-width: calc(100% - 1px);
height: 17px;
border-radius: 15px;
}
This is how I try to update it:
document.getElementById(gName+"-pbar").style.setProperty('--width', calculatedPercent);
If I make a log, the new percentage is displayed correctly in the log, but the property of the element is not modified:
The element:
The element image
The log:
The log image
The code that you posted seems to work fine, the problem must be something else.
Here is the example working:
let progress = 0;
setInterval(() => {
if (++progress > 100) progress = 0;
document.getElementById("test").style.setProperty('--width', progress);
}, 100);
:root {
--progressbar-main-color: crimson;
}
.progressBarContainer {
width: 100%;
background-color: darkgray;
}
.progressBarPercent {
background-color: var(--progressbar-main-color);
width: calc(var(--width, 0) * 1%);
min-width: 10px;
max-width: calc(100% - 1px);
height: 17px;
border-radius: 15px;
}
<div class="progressBarContainer percentBar">
<div class="progressBarPercent" style="--width:0" id="test"></div>
</div>

Change the colour of a triangle div over time

EDIT: https://codepen.io/TechTime/pen/NjZOGE This is what I want to achieve, happening every few random amount of seconds with random colors.
EDIT2: How would this be done with multiple triangles? I've tried a few things, but it hasn't worked. Help would be appreciated
I was wandering if it were possible to change the color of a triangle div so that every few seconds it would glow a color then go back to normal. Below is my triangle code:
.triangle-up {
z-index: 1;
float: left;
margin: 0.5%;
width: 5%;
height: 0;
padding-left: 5%;
padding-bottom: 5%;
overflow: hidden;
}
.triangle-up:after {
content: "";
display: block;
width: 0;
height: 0;
margin-left: -500px;
border-left: 500px solid transparent;
border-right: 500px solid transparent;
border-bottom: 500px solid #e6e6e6;
}
I don't mind if it uses css, javascript or jquery. Just that it works! Thanks in advance.
The accepted solution does not meet all the criteria currently requested by the OP, I believe this one does and those being:
Random colors.
Random time intervals.
Return to initial color.
"Glows".
We use JS to change bottom border color and transition duration to random values. We also respond to the transitionend event so we don't have to use setInterval and know that the transition between colors has fully completed. Every other transition returns to the default gray. Glows by fading between colors instead of the color instantly changing to next color.
I've done this through a function that allows you to assign the element that requires the animation/transition and min/max parameters to control the time interval range between color changes. You'll also notice that I removed the pseudo element and nested a regular DIV as changing pseudo element CSS properties can be tricky.
var colorizer = function ( el, min, max ) {
// #link https://stackoverflow.com/questions/5092808/how-do-i-randomly-generate-html-hex-color-codes-using-javascript
function getHexColor() {
return "#000000".replace( /0/g, function () {
return ( ~~( Math.random() * 16 ) ).toString( 16 );
} );
}
// #link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
function getRandomInt( min, max ) {
return Math.floor( Math.random() * ( max - min + 1 ) ) + min;
}
min = undefined == min ? 250 : min;
max = undefined == max ? 1500 : max;
var isDefaultColor = true,
style = el.style,
defaultColor = style.borderBottomColor,
color;
return function ( e ) {
el.offsetWidth; // Reset transition so it can run again.
color = isDefaultColor ? getHexColor() : defaultColor;
isDefaultColor = !isDefaultColor;
style.borderBottomColor = color;
style.transitionDuration = ( getRandomInt( min, max ) ) + 'ms';
};
},
triangle = document.querySelector( '.triangle > div' ),
triangleColorizer = colorizer( triangle, 750, 2000 );
triangle.addEventListener( 'transitionend', triangleColorizer );
// Kick it off!
triangleColorizer();
.triangle {
width: 5%;
height: 0;
padding: 0 0 5% 5%;
overflow: hidden;
}
.triangle > div {
width: 0;
height: 0;
margin-left: -500px;
border-right: 500px solid transparent;
border-left: 500px solid transparent;
border-bottom: 500px solid lightgray;
transition: border-bottom-color 1000ms ease-in-out;
}
<div class="triangle">
<div></div>
</div>
This changes the triangle color into a random color every 2 seconds. On the first function we iterate on a string of letters and return it with as a random hex code. The x function creates a style tag and appends it into the head tag then it toggles the class randColor defined inside the previous statement. Finally the setInterval function is called calling the functions every 2 seconds. The remover function just removes the style tag from the head so we don't keep appending style tags every 2 seconds. It changes color every 2 seconds then goes back to its original color. Hope this helps.
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function remover(){
$(".style-tag").remove();
}
function x(){
var style = $('<style class="style-tag">.randColor:after { border-bottom: 500px solid ' + getRandomColor() +'; }</style>');
$('html > head').append(style);
$(".triangle-up").toggleClass("randColor");
}
$(document).ready(function(){
setInterval(function(){
remover();
x();
}, 2000);
});
.triangle-up {
z-index: 1;
float: left;
margin: 0.5%;
width: 5%;
height: 0;
padding-left: 5%;
padding-bottom: 5%;
overflow: hidden;
}
.triangle-up:after {
content: "";
display: block;
width: 0;
height: 0;
margin-left: -500px;
border-left: 500px solid transparent;
border-right: 500px solid transparent;
border-bottom: 500px solid #e6e6e6;
transition: all 0.4s ease-in-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="triangle-up"></div>
So this is very crude, but the only way I see this possible is using jQuery and having a bunch of css classes. You cannot change the :after css rule via jquery, since it's not part of the dom. But we can do something like this (which I admit is tedious, but I don't quite see another way given your current html).
html
<div class="triangle-up blue">
</div>
jquery
var cachedColorName;
$(document).ready(function() {
setInterval(function(){
var newColor = 'red'; //(here you'd want to randomnly find a color that you have in your css
changeColor(newColor);
}, 3000);});
function changeColor(colorName) {
$('.triangle-up').removeClass(cachedColorName).addClass(colorName);
cachedColorName = colorName;
}
css
.triangle-up {
z-index: 1;
float: left;
margin: 0.5%;
width: 5%;
height: 0;
padding-left: 5%;
padding-bottom: 5%;
overflow: hidden;
}
.triangle-up:after {
content: "";
display: block;
width: 0;
height: 0;
margin-left: -500px;
border-left: 500px solid transparent;
border-right: 500px solid transparent;
}
.triangle-up.blue:after {
border-bottom: 500px solid blue;
}
.triangle-up.red:after{
border-bottom: 500px solid red;
}
So you're just toggling different classes here. But this is the only way to make it random like you want (instead of hardcoded red that I did, you can programmatically pick a random color each time from a collection you have that has all the css classes that accompanies it).
Here's it in action:
https://jsfiddle.net/5b7wLv3r/2/
EDIT: if you need help randomly selecting a color, let me know. I can add that code.
EDIT 2: I made this a bit smarter for you
EDIT 3: finding the random color
css
.triangle-up {
z-index: 1;
float: left;
margin: 0.5%;
width: 5%;
height: 0;
padding-left: 5%;
padding-bottom: 5%;
overflow: hidden;
}
.triangle-up:after {
content: "";
display: block;
width: 0;
height: 0;
margin-left: -500px;
border-left: 500px solid transparent;
border-right: 500px solid transparent;
}
.triangle-up.blue:after {
border-bottom: 500px solid blue;
}
.triangle-up.red:after{
border-bottom: 500px solid red;
}
.triangle-up.purple:after{
border-bottom: 500px solid purple;
}
.triangle-up.yellow:after{
border-bottom: 500px solid yellow;
}
.triangle-up.orange:after{
border-bottom: 500px solid orange;
}
.triangle-up.green:after{
border-bottom: 500px solid green;
}
html
<div class="triangle-up blue">
</div>
js
var cachedColorName;
var colorCollection = ['red', 'blue', 'purple', 'yellow', 'orange', 'green']
$(document).ready(function() {
setInterval(function(){
var newColor = randomItem(colorCollection); //(here you'd want to randomnly find a color that you have in your css
changeColor(newColor);
}, 3000);});
function changeColor(colorName) {
$('.triangle-up').removeClass(cachedColorName);
$('.triangle-up').addClass(colorName);
cachedColorName = colorName;
}
function randomItem(collection) {
return collection[Math.floor(Math.random()*collection.length)];
}
So basically, we have a collection here, which we randomly find a value in it, then pass the color name to our changeColor method. I did see in your question you want to change to random color, then back to default. Let me know if you need me to help you with that as well, basically just a boolean to see if you changed to random before. I would have implemented this in the code, but since you did not try it on your own I want to leave something up to you to figure out if so, just change to default. Otherwise, find the random color.
Working here:
https://jsfiddle.net/5b7wLv3r/3/

How to monitor what the user clicks

I am currently having trouble figuring out how am i supposed to monitor every click of the user.
My little game does this :
You have 5 buttons, 1 start button and 4 buttons that will be highlighted in a random order.
After that i want the user to click the buttons in the order that they have been highlighted (in 10 seconds time, i haven't implemented the 10 seconds time yet).
I don't know how to restrict the user to only be able to press buttons only in the given time and to see what buttons he presses just with JavaScript and Jquery (if you can't restrict at least to see what buttons he presses ).
I will then retain the order in which he pressed the buttons in the array "input" .
Here is my code :
HTML :
<!DOCTYPE html>
<html lang="ro">
<head>
<link href="my.css" type="text/css" rel="stylesheet">
<script type="text/javascript" src="jquery-1.11.0.js"></script>
<script src="Joculet.js" type="text/javascript"> </script>
<meta charset="utf-8">
<title> Joculet </title>
</head>
<body>
<div id ='tot'>
<button type='button' class='cls1' id='id1'></button>
<button type='button' class='cls2' id='id2'></button>
<button type='button' class='cls3' id='id3'></button>
<button type='button' class='cls4' id='id4'></button>
<button type='button' id='start'>Click Me!</button>
</div>
</body>
</html>
CSS:
.tot{
position: absolute;
width: 100%;
height: 100%;
}
.cls1{
position: absolute;
background-color: red;
width: 12%;
height: 12%;
border: 2px solid black;
}
.cls2{
position: absolute;
background-color: yellow;
width: 12%;
height: 12%;
border: 2px solid black;
margin-left: 17%;
}
.cls3{
position: absolute;
background-color: #00FF00;
width: 12%;
height: 12%;
border: 2px solid black;
margin-top: 12%;
}
.cls4{
position: absolute;
background-color: #3090C7;
width: 12%;
height: 12%;
border: 2px solid black;
margin-left: 17%;
margin-top: 12%;
}
#start{
position: absolute;
margin-left: 12%;
margin-top: 23%;
}
.cls12{
position: absolute;
background-color: #C24641;
width: 12%;
height: 12%;
border: 2px solid black;
}
.cls22{
position: absolute;
background-color: #FFFFCC;
width: 12%;
height: 12%;
border: 2px solid black;
margin-left: 17%;
}
.cls32{
position: absolute;
background-color: #6AFB92;
width: 12%;
height: 12%;
border: 2px solid black;
margin-top: 12%;
}
.cls42{
position: absolute;
background-color: #893BFF;
width: 12%;
height: 12%;
border: 2px solid black;
margin-left: 17%;
margin-top: 12%;
}
and the most important JS :
var k = 1;
var g = 1;
var nrmax = 8;
ordine = new Array();
var j = 0;
input = new Array();
$(document).ready(function () {
$('#start').click(function () {
game();
})
function game() {
if(k <= nrmax){
if(g <= k){
var x = Math.floor((Math.random() * 4) + 1);
ordine[j++] = x;
change1(x);
}
else {
alert('Felicitari ai castigat runda');
g = 1;
k++;
j = 0;
ordine = new Array();
setTimeout(function(){game();},2000);
}
}
else alert('Felicitari ai castigat jocul');
}
function change1(y) {
var z = 'cls' + y;
var t = 'cls' + y + 2;
$("." + z).removeClass(z).addClass(t);
setTimeout(function() { change2(y); }, 500);
}
function change2(y) {
var z = 'cls' + y + 2;
var t = 'cls' + y;
$("." + z).removeClass(z).addClass(t);
g++;
setTimeout(function(){game();},500);
}
});
any help is apreciated, you can also find the code here for a better view http://jsfiddle.net/6qDap/1181/
I think I understood your questions correctly. I did not include the timer but here is how you could maintain the order of clicked buttons in the input array.
http://jsfiddle.net/6qDap/1184/
$('button').click(function(){
input.push( $(this).attr('id') );
console.log(input);
});
Don't forget to check the console to view the output. Hope this helps! Let me know if you have any questions or if I misunderstood.
If I understand you right - you want to time a user clicking 4 buttons within 10 sec. I would start a javascript timer when the user clicks start.
setTimeout(disablebuttonsaftertimeout, 10000);
Then disable the buttons after the timer expires.
"I don't know how to restrict the user to only be able to press buttons only in the given time and to see what buttons he presses" - are asking two things here
I don't know how to restrict the user to only be able to press buttons only in the given time - if time is over, disable/hide buttons
see what buttons he presses - every time he presses a button store the id of a button in the array
also to restrict the user from pressing any other buttons, add a class "wrong" to buttons that he can't press and on click check if $(this).hasClass('wrong') return 0;

Categories

Resources