Increasing a progress bar by clicking a button - javascript

The idea is that the progress bar should increase when you click the button, for example, if you click on the button play the happiness should increase.
const cleanBtn = document.querySelector(".clean");
const feadBtn = document.querySelector(".fead");
const playBtn = document.querySelector(".play");
cleanBtn.addEventListener("click", () => {
let health = document.getElementById("myHappines");
health.style.width = 0;
if (health.style.width > 100 % ) {
health.style.width = 0 % ;
else {
health.style.width += 10 % ;
}
}
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Virtual Pet</title>
<!--font-awesome-->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" />
<!--styles-->
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="sections-container">
<div class="section1">
<div class="pet-info">
<ul>
<div id="basic">
<ul>Name: Elis</ul>
<ul>Age: 2 months</ul>
</div>
<div class="health">Health
<div id="myProgressHealth">
<div id="myHealth"></div>
</div>
</div>
<div class="hunger">Hunger
<div id="myProgressHunger">
<div id="myHunger"></div>
</div>
</div>
<div class="happiness">Happiness
<div id="myProgressHappiness">
<div id="myHappiness"></div>
</div>
</div>
</ul>
</div>
<button class="btn-settings">Settings</button>
</div>
<div class="section2">
<div class="pet-interactions">
<ul>
<button class="clean">Clean</button>
<button class="fead">Fead</button>
<button class="play">Play</button>
</ul>
</div>
<div class="game-control">
<li id="name-input">Pet Name <input type="text"></input></li>
<li>Game reset button <button class="btn">Reset</button></li>
</div>
<div class="end-game-message">
<p>Goodbye</p>
</div>
</div>
</div>
<!--javascript-->
<script src="app.js"></script>
</body>
</html>

There are many issues and typos in your code. Clean programming will solve them all.
You want a bar for which HTML has a specific tag for: <progress>. Use it instead of divs!
Use a ternary conditional operator to check if the value is 100 or below and then reset the health bar or add 10% to it:
const cleanBtn = document.querySelector('.clean');
cleanBtn.addEventListener('click', () => {
let health = document.getElementById('myHappiness');
health.value = (health.value === health.max) ? 0 : health.value + 10;
})
<button class="clean">Clean</button>
<br>
<label for"myHappyness">Happiness:</label><progress id="myHappiness" value ="0" max="100"></progress>
The main issue with your code where the many typos. Among that was that you used < 100 % which will divide 100 by an undefined amount and look for the remainder. % is used as a calculation for a remainder (100 % 3 = 1) . To use 100% in the way you intended to, you have to use it as a string.

I think this would be a better approach:
var happiness = 2;
document.getElementById("demo").textContent = happiness
function increaseHappiness() {
happiness++
document.getElementById("demo").textContent = happiness
}
<div>
Happyness: <span id=demo></span>
</div>
<br>
<button onClick="increaseHappiness()">More Happy</button>

the first mistake you have made that you enter integer value in
element.style.width = 10 thats wrong you should enter string value like this element.style width = "10%";
the same thing about your if(element.style.width === 100%)
thats wrong because elment.style.width return string number not int so you compare string with number its always will return false you do that instead if(parseInt(health.style.width) > 100 ) parseInt is method that change string to integer if it possible. hope that usefull
let playBtn = document.getElementById("playBtn");
let newWidth = 0
playBtn.addEventListener("click", ()=>{
let health = document.getElementById("myHappiness");
if(parseInt(health.style.width) > 100 )
{
health.style.width = "0%";
newWidth = 0;
}
else{
newWidth += 10;
health.style.width = newWidth + "%"
}
})
<div class="sections-container">
<div class="section1">
<div class="pet-info">
<ul>
<div id="basic">
<ul>Name: Elis</ul>
<ul>Age: 2 months</ul>
</div>
<div class="health">Health
<div id="myProgressHealth" >
<div id="myHealth"></div>
</div>
</div>
<div class="hunger">Hunger
<div id="myProgressHunger">
<div id="myHunger"></div>
</div>
</div>
<div class="happiness" >Happiness
<div id="myProgressHappiness">
<div id="myHappiness" style="height:10px;background:red;width:0;"></div>
</div>
</div>
</ul>
</div>
<button class="btn-settings">Settings</button>
</div>
<div class="section2">
<div class="pet-interactions">
<ul>
<button class="clean">Clean</button>
<button class="fead">Fead</button>
<button class="play" id = "playBtn">Play</button>
</ul>
</div>
<div class="game-control">
<li id="name-input">Pet Name <input type="text"></input></li>
<li>Game reset button <button class="btn">Reset</button></li>
</div>
<div class="end-game-message">
<p>Goodbye</p>

Related

Add anchor tags dynamically to a div when page load in Javascript

I have 2 divs that all have the same css class, as follows:
/*div 1 */
<div class="oxilab-flip-box-col-5 oxilab-flip-box-padding-1" >
<div class="oxilab-flip-box-body-1 oxilab-flip-box-body-1-1">
<div class="oxilab-flip-box-body-absulote">
<div class="oxilab-flip-box-flip oxilab-flip-box-flip-left-to-right">
<div class="oxilab-flip-box-style-data easing_easeInOutCirc">
<div class="oxilab-flip-box-style">
<div class="oxilab-flip-box-front">
<div class="oxilab-flip-box-1">
<div class="oxilab-flip-box-1-data">
</div>
</div>
</div>
<div class="oxilab-flip-box-back">
<div class="oxilab-flip-box-back-1">
<div class="oxilab-flip-box-back-1-data">
<div class="oxilab-heading" googl="true">
heading
</div>
<div class="oxilab-info">
some text
</div>
<a href="http://test.com" target="">
<span class="oxilab-button">
<span class="oxilab-button-data">
enter
</span>
</span>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
/*div 2 */
<div class="oxilab-flip-box-col-5 oxilab-flip-box-padding-1" >
<div class="oxilab-flip-box-body-1 oxilab-flip-box-body-1-1">
<div class="oxilab-flip-box-body-absulote">
<div class="oxilab-flip-box-flip oxilab-flip-box-flip-left-to-right">
<div class="oxilab-flip-box-style-data easing_easeInOutCirc">
<div class="oxilab-flip-box-style">
<div class="oxilab-flip-box-front">
<div class="oxilab-flip-box-1">
<div class="oxilab-flip-box-1-data">
</div>
</div>
</div>
<div class="oxilab-flip-box-back">
<div class="oxilab-flip-box-back-1">
<div class="oxilab-flip-box-back-1-data">
<div class="oxilab-heading" googl="true">
heading
</div>
<div class="oxilab-info">
some text
</div>
<a href="http://example.com" target="">
<span class="oxilab-button">
<span class="oxilab-button-data">
enter
</span>
</span>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
As you can see, both main divs have oxilab-flip-box-col-5 class and each has an ahref tag, now I want all the div components to be linked when the page is loaded, as follows:
/*div 1 */
<a href="http://test.com" target="">
<div class="oxilab-flip-box-col-5 oxilab-flip-box-padding-1" >
.
.
.
</div>
</a>
/*div 2 */
<a href="http://example.com" target="">
<div class="oxilab-flip-box-col-5 oxilab-flip-box-padding-1" >
.
.
.
</div>
</a>
I was able to write this code with JavaScript, but unfortunately, the code I wrote does not work.
var fisrtdiv = document.getElementsByClassName("oxilab-flip-box-col-5");
var aTag = document.createElement('a');
aTag.setAttribute('href',"http://test.com");
aTag.innerText = "some text";
fisrtdiv.appendChild(aTag);
var seconddiv = document.getElementsByClassName("oxilab-flip-box-col-5");
var aTag = document.createElement('a');
aTag.setAttribute('href',"http://example.com");
aTag.innerText = "some text";
seconddiv.appendChild(aTag);
Any idea how I can do this and link each div separately ?
Here You Go:
var first_div = document.getElementsByClassName("oxilab-flip-box-col-5")[0];
var parent1 = first_div.parentNode;
var a_tag1 = document.createElement('a');
parent1.replaceChild(a_tag1, first_div)
a_tag1.appendChild(first_div)
a_tag1.setAttribute('href',"http://example.com");
/////////
var second_div = document.getElementsByClassName("oxilab-flip-box-col-5")[1];
var parent2 = second_div.parentNode;
var a_tag2 = document.createElement('a');
parent2.replaceChild(a_tag2, second_div)
a_tag2.appendChild(second_div)
a_tag2.setAttribute('href',"http://example.com");
getElementsByClassName return an HTMLCollection of elements.
Change your code to:
var fisrtdiv = document.getElementsByClassName("oxilab-flip-box-col-5")[0];
var aTag = document.createElement('a');
aTag.setAttribute('href',"http://test.com");
aTag.innerText = "some text";
fisrtdiv.appendChild(aTag);
var seconddiv = document.getElementsByClassName("oxilab-flip-box-col-5")[1];
var aTag = document.createElement('a');
aTag.setAttribute('href',"http://example.com");
aTag.innerText = "some text";
seconddiv.appendChild(aTag);
You should try to DRY (Don't Repeat Yourself). You can see that you do 2 times the same thing. What if you need to do it 100 times? Then your code will get messy quickly.
You'll see 2 solutions in my code: the ugly way (not DRY) and the cleaner way (DRY). There's a even cleaner way but let's start with this ;)
/*THE UGLY WAY*/
/*
var fisrtdiv = document.getElementsByClassName("oxilab-flip-box-col-5")[0];
var first_link = document.createElement('a');
first_link.setAttribute('href',"http://test.com");
first_link.innerText = "some text1";
first_link.append(fisrtdiv);
document.body.append(first_link);
//we take again at index 0 because before this line we changed the position of the flip boxes
var seconddiv = document.getElementsByClassName("oxilab-flip-box-col-5")[0];
var second_link = document.createElement('a');
second_link.setAttribute('href',"http://example.com");
second_link.innerText = "some text2";
second_link.append(seconddiv);
document.body.append(second_link);
*/
/*CLEANER WAY*/
var
list_of_flip_boxes = document.querySelectorAll(".oxilab-flip-box-col-5"),
list_of_links = [
{
text : "some text 1",
href : "http://test.com"
},
{
text : "some text 2",
href : "http://example.com"
},
];
list_of_flip_boxes.forEach(function(flip_box, index){
var
link_element = document.createElement("a"),
link_data = list_of_links[index];
link_element.setAttribute('href', link_data.href);
link_element.innerText = link_data.text;
link_element.append(flip_box);
document.body.append(link_element);
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
</head>
<body>
<div class="oxilab-flip-box-col-5 oxilab-flip-box-padding-1" >
<div class="oxilab-flip-box-body-1 oxilab-flip-box-body-1-1">
<div class="oxilab-flip-box-body-absulote">
<div class="oxilab-flip-box-flip oxilab-flip-box-flip-left-to-right">
<div class="oxilab-flip-box-style-data easing_easeInOutCirc">
<div class="oxilab-flip-box-style">
<div class="oxilab-flip-box-front">
<div class="oxilab-flip-box-1">
<div class="oxilab-flip-box-1-data">
</div>
</div>
</div>
<div class="oxilab-flip-box-back">
<div class="oxilab-flip-box-back-1">
<div class="oxilab-flip-box-back-1-data">
<div class="oxilab-heading" googl="true">
heading
</div>
<div class="oxilab-info">
some text
</div>
<a href="http://test.com" target="">
<span class="oxilab-button">
<span class="oxilab-button-data">
enter
</span>
</span>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="oxilab-flip-box-col-5 oxilab-flip-box-padding-1" >
<div class="oxilab-flip-box-body-1 oxilab-flip-box-body-1-1">
<div class="oxilab-flip-box-body-absulote">
<div class="oxilab-flip-box-flip oxilab-flip-box-flip-left-to-right">
<div class="oxilab-flip-box-style-data easing_easeInOutCirc">
<div class="oxilab-flip-box-style">
<div class="oxilab-flip-box-front">
<div class="oxilab-flip-box-1">
<div class="oxilab-flip-box-1-data">
</div>
</div>
</div>
<div class="oxilab-flip-box-back">
<div class="oxilab-flip-box-back-1">
<div class="oxilab-flip-box-back-1-data">
<div class="oxilab-heading" googl="true">
heading
</div>
<div class="oxilab-info">
some text
</div>
<a href="http://example.com" target="">
<span class="oxilab-button">
<span class="oxilab-button-data">
enter
</span>
</span>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>

URL display:none;

I have this code, for some reason when I try to access it with a link (http://127.0.0.1:5501/111.html?textarea=2&p=2) the textarea part remains the same, I'm probably doing something wrong, but I'm not sure how to fix it.
When I open the link I want to see textarea 2 and p 2 visible, the rest should be hidden.
Here is the code in case someone from the forum can help:
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="stylechat.css">
<meta charset="UTF-8">
<title>Support</title>
<meta http-equiv="Content-Type">
</head>
<body data-new-gr-c-s-check-loaded="14.1022.0" data-gr-ext-installed="">
<!-- nav -->
<div class="navbar">
<div class="container">
<a class="logo" href="./index.html">Ho<span>me</span></a>
</div>
</div>
<!-- nav -->
<!-- info -->
<div class="textinfo">
<p class="menus" id="dsk1"><span>AAA:</span><br>
One:<br><br>
1. test<br>
2. test<br></p>
</div>
<div class="textinfo">
<p class="menus" id="dsk2"><span>AAA:</span><br>
Two:<br><br>
1. test<br>
2. test<br></p>
</div>
<!-- info -->
<!-- text -->
<div class="textniz">
<textarea id="myInput1" class="one" name="myInput1" readonly>
One
One
One</textarea>
</div>
<div class="textniz">
<textarea id="myInput2" class="two" name="myInput2" readonly>
Two
Two
Two</textarea>
</div>
<div class="textniz">
<textarea id="myInput3" class="three" name="myInput3" readonly>
Three
Three
Three</textarea>
</div>
<div class="textniz">
<textarea id="myInput4" class="four" name="myInput4" readonly>
Four
Four
Four</textarea>
</div>
<div class="textniz">
<textarea id="myInput5" class="five" name="myInput5" readonly>
Five
Five
Five</textarea>
</div>
<div class="textniz">
<textarea id="myInput6" class="six" name="myInput6" readonly>
Six
Six
Six</textarea>
</div>
<div class="textniz">
<textarea id="myInput7" class="seven" name="myInput7" readonly>
Seven
Seven
Seven</textarea>
</div>
<div class="textniz">
<textarea id="myInput8" class="eight" name="myInput8" readonly>
Eight
Eight
Eight</textarea>
</div>
<!-- text -->
<!-- scr -->
<div class="scrn" id="scrn">
<img src="/Screenshot_1.png" alt="" class="image1"></img>
<img src="/Screenshot_2.png" alt="" class="image2"></img>
<img src="/Screenshot_3.png" alt="" class="image3"></img>
<img src="/Screenshot_5.png" alt="" class="image4"></img>
</div>
<!-- scr -->
<!-- button -->
<button onclick="showscr(1)" id="scr1" class="scron1"></button>
<button onclick="showscr(2)" id="scr2" class="scron2"></button>
<button onclick="Copytextfunction(1)" id="menucopy1" class="menucopy1"></button>
<button onclick="Copytextfunction(2)" id="menucopy2" class="menucopy2"></button>
<button onclick="Copytextfunction(3)" id="menucopy3" class="menucopy3"></button>
<button onclick="Copytextfunction(4)" id="menucopy4" class="menucopy4"></button>
<button onclick="Copytextfunction(5)" id="menucopy5" class="menucopy5"></button>
<button onclick="Copytextfunction(6)" id="menucopy6" class="menucopy6"></button>
<button onclick="Copytextfunction(7)" id="menucopy7" class="menucopy7"></button>
<button onclick="Copytextfunction(8)" id="menucopy8" class="menucopy8"></button>
</div>
<!-- button -->
<!-- script -->
<script>
// Get textarea from url parameters
const urlParams = new URLSearchParams(window.location.search);
let textarea = urlParams.get('textarea')
function show(textarea) {
for (let check = 1; check <= 8; check++) {
document.getElementById('myInput' + check).style.display = "none";
document.getElementById('menucopy' + check).style.display = "none";
}
document.getElementById('myInput' + textarea).style.display = "block";
document.getElementById('menucopy' + textarea).style.display = "block";
}
let p = urlParams.get('p')
function show(p) {
for (let check = 1; check <= 2; check++) {
document.getElementById('dsk' + check).style.display = "none";
document.getElementById('dsk' + check).style.display = "none";
}
document.getElementById('dsk' + p).style.display = "block";
document.getElementById('dsk' + p).style.display = "block";
}
function Copytextfunction(textarea) {
var value = document.getElementById('myInput' + textarea).value;
var copyText = document.createElement("textarea");
copyText.value = value;
copyText.style.position = "fixed";
copyText.style.top = "-1000vh";
document.body.append(copyText);
copyText.select();
copyText.setSelectionRange(0, 99999)
document.execCommand("copy");
console.log(value);
copyText.remove();
}
// Run the hide function with the textarea number from parameters
if (textarea) {
show(textarea);
}
if (p) {
show(p);
}
</script>
<!-- script -->
</body>

Show different images onClick event (JavaScript)

So, I don't have any working knowledge of JavaScript, but I am wondering why this does not work for me. I have 4 buttons, 4 different divs with different images, when one button is clicked I would like the images to change to the category which is displayed on the button.
i.e Button: "Windows" --Button is clicked--> Show images of windows
Button "Doors" --Button is clicked--> show images of Doors
JavaScript file is imported to HTML document:
<head>
<script type="text/javascript" src="script.js"></script>
</head>
const showChoosenCategory = event => {
const getId = event.id
const links = document.querySelectorAll('.work-category button')
for (i = 0; i < links.length; i++) {
if (links[i].hasAttribute('class')) {
links[i].classList.remove('active')
}
}
event.classList.add('active')
const getCategory = document.querySelector(`.category-${getId}`)
const categories = document.querySelectorAll('div[class ^= "category-"]')
for (i = 0; i < categories.length; i++) {
if (categories[i].hasAttribute('class')) {
categories[i].classList.remove('showCategory')
categories[i].classList.add('hideCategory')
}
}
getCategory.classList.remove('hideCategory')
getCategory.classList.add('showCategory')
}
.hideCategory {
display: none;
}
<div class="gallery" id="gallery">
<div class="work-category">
<button class="category active" id="windows">Fönster</button>
<button class="category" id="doors">Dörr</button>
<button class="category" id="furniture">Möbler</button>
<button class="category" id="misc">Övrigt</button>
</div>
<div class="category-windows showCategory">
<div class="imageslist">
<img src="assets/img_window.jpg" class="gallery-image">
</div>
</div>
<div class="category-doors hideCategory">
<div class="imageslist">
<img src="assets/img_door.jpg" class="gallery-image">
</div>
</div>
<div class="category-furniture hideCategory">
<div class="imageslist">
<img src="assets/img_furniture.jpg" class="gallery-image">
</div>
</div>
<div class="category-misc hideCategory">
<div class="imageslist">
<img src="assets/img_misc.jpg" class="gallery-image">
</div>
</div>
</div>
How Can I make this work?
This is a small solution based on the script you provided.
I have modified/added some attributes in order to simplify the script.
The logic is the following:
the button dictates which div is going to be display
var controls = document.querySelector('.work-category');
var gallery = document.querySelector('.gallery');
controls.addEventListener('click', displayCategory);
function displayCategory(ev) {
var selectedControl = controls.querySelector('.active');
var activeCategory = gallery.querySelector('.showCategory');
// exiting early if the selected control
// is the clicked button
if (ev.target === selectedControl) { return; }
var categoryId = ev.target.dataset.category;
var category = gallery.querySelector('.category-' + categoryId);
ev.target.classList.add('active');
category.classList.add('showCategory');
selectedControl.classList.remove('active');
activeCategory.classList.remove('showCategory');
}
.active {
background: skyblue;
}
.category-windows,
.category-doors,
.category-furniture,
.category-misc {
display: none;
}
.showCategory {
display: block;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="gallery" id="gallery">
<div class="work-category">
<button class="category active" data-category="windows">Fönster</button>
<button class="category" data-category="doors">Dörr</button>
<button class="category" data-category="furniture">Möbler</button>
<button class="category" data-category="misc">Övrigt</button>
</div>
<div class="category-windows showCategory">
<div class="imageslist">
<img src="assets/img_window.jpg" alt="window" class="gallery-image">
</div>
</div>
<div class="category-doors">
<div class="imageslist">
<img src="assets/img_door.jpg" alt="door" class="gallery-image">
</div>
</div>
<div class="category-furniture">
<div class="imageslist">
<img src="assets/img_furniture.jpg" alt="furniture" class="gallery-image">
</div>
</div>
<div class="category-misc">
<div class="imageslist">
<img src="assets/img_misc.jpg" alt="misc" class="gallery-image">
</div>
</div>
</div>
</body>
</html>

Typing Game-- Want all letters typed to be lower case

I'm trying to convert all letters that are typed in the field to be lower case. I know this is simple but for the life of me, I can't get it to work. I thought if I put "word-input.toLowerCase()" under the match words function that it should make the letter lowercase but it didn't work. Here's what I have:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/css/bootstrap.min.css"> -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css">
<title>One Piece WordBeater</title>
</head>
<body>
<body class="bg-dark text-white">
<header class="bg-secondary text-center p-3 mb-5">
<h1>One Piece Word Beater</h1>
</header>
<div class="container text-center">
<!--Word & Input-->
<div class="row">
<div class="col-md-3 mx-auto">
<p class="lead">Current Level: <span class="text-info" id="levels"></span></p>
</div>
<div class="col-md-6 mx-auto">
<p class="lead">Type the Given Word Within <span class="text-success" id="seconds">5</span> Seconds. </p>
<h2 class="display-2 mb-5" id="current-word">luffy</h2>
<input type="text" class="form-control form-control-lg" placeholder="Start Typing..." id="word-input" autofocus>
<h4 class="mt-3" id="message"></h4>
<br>
<div class="btn-group">
<button type="button" class="btn btn-warning mr-5" id="start"><b>Let's Play!</b></button>
<button type="button" class="btn btn-danger" id="reset"><b>Reset Game</b></button>
</div>
</div>
<div class="col-md-3 mx-auto">
<p class="lead">High Score: <span class="text-info" id="highsocre"></span></p>
</div>
</div>
<!--Time and Columns-->
<div class="row mt-5">
<div class="col md-6">
<h3>Time left: <span id="time">0</span></h3>
</div>
<div class="col md-6">
<h3>Score: <span id="score"> 0 </span></h3>
</div>
</div>
<!--Instructions-->
<div class="row mt-5">
<div class="col md-12">
<div class="card card-body bg-secondary text-white">
<h5>Instructions</h5>
<p>Type each word in the given amount of seconds to score. To play again, just type the current word. Your score
will reset</p>
</div>
</div>
</div>
<!--Level Selector-->
<div class = "row mt-5">
<div class="col md-12">
<div class="card card-body bg-secondary text-white">
<h5>Select the Difficulty</h5>
<div class="row mt-5">
<div class="col md-12">
<div class="btn-group">
<button type="button" class="btn btn-success mr-2" id="easy">Easy</button>
<button type="button" class="btn btn-primary mr-2" id="medium">Medium</button>
<button type="button" class="btn btn-danger" id="hard">Hard</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/js/bootstrap.min.js"></script>
<script src="index.js"></script>
</body>
</html>
// window.addEventListener('load', init);
//Start Game
// const startbtn = document.getElementById('start');
// global Varibales
//Avaible levels
const levels = {
easy: 5,
medium: 3,
hard: 2,
}
//to cchange level
const currentLevel = levels.easy;
let time = currentLevel;
let score = 0;
let isPLaying;//initalzies game...true if game is on false if game is off
//DOM Elements
const wordInput = document.querySelector('#word-input');
const currentWord = document.querySelector('#current-word');
const scoreDisplay = document.querySelector('#score');
const timeDisplay = document.querySelector('#time');
const message = document.querySelector('#message');
const seconds = document.querySelector('#seconds');
const levelDisplay = document.querySelector('#levels');
const words = [
'luffy',
'zoro',
'shanks',
'nami',
'brook',
'chooper',
'sanji',
'franky',
'jinbe',
'carrot',
'pekoms',
'ace',
'sabo',
'robin',
'bellamy',
'crocodile',
'merry',
'yonko',
'camie',
'nefertari',
'raizo',
'momo',
'law',
'dracule',
'boa',
'buggy',
'golroger',
'bigmom',
'smoker',
'kaido'
];
//initialize Game
// function init() {
// //Show number of seconds
// seconds.innerHTML = currentLevel;
// //load a word from array
// showWord(words);
// //Start Matching on word input
// wordInput.addEventListener('input', startMatch);
// //Call countdown every second
// setInterval(countdown, 1000);
// //Check status
// setInterval(checkStatus, 50)
// }
window.onload = function init() {
//start button
const startBtn = document.getElementById('start')
startBtn.onclick = function() {
//Show number of seconds
seconds.innerHTML = currentLevel;
//load a word from array
showWord(words);
//Start Matching on word input
wordInput.addEventListener('input', startMatch);
//Call countdown every second
setInterval(countdown, 1000);
//Check status
setInterval(checkStatus, 50)
}
}
//level Buttons
//Easy Mode
// document.getElementById('easy').addEventListener('click', easyMode);
// function easyMode(levels) {
// }
//Start Match
function startMatch() {
if(matchWords()){
isPLaying = true;
time = currentLevel + 1;
showWord(words);
wordInput.value='';
score++;
}
//if score negative -1 display 0
if(score === -1){
scoreDisplay.innerHTML = 0;
}else{
scoreDisplay.innerHTML = score;
}
}
//Match Current Word to word imput
function matchWords(){
if(wordInput.value === currentWord.innerHTML) {
message.innerHTML = 'Correct!!!';
return true;
} else {
message.innerHTML = '';
return false;
}
}
//Pick & Show random word
function showWord(words) {
//Generate random array index
const randIndex = Math.floor(Math.random() * words.length);
//Output random word
currentWord.innerHTML = words[randIndex];
}
//Countdown Timer
function countdown() {
//Make sure time is not run out
if(time > 0) {
//Decrease time
time--;
}else if(time === 0) {
//Game Over
isPLaying = false;
}
//Show time
timeDisplay.innerHTML = time;
}
//Check game Status
function checkStatus() {
if(!isPLaying && time === 0){
message.innerHTML = 'Game Over!!';
score = -1;
}
}
//reset after game over
You can do this simply using CSS
<input type="text" class="lowercase" name="input" />
and in the css file do
.lowercase { text-transform: lowercase }
However, there's a down side to this. The value being sent to the backend will still be in the actual case the text was entered.
If you want to make sure you send the input to the backend in the lowercase I suggest using javascript to turn the string to lowercase.
So, in your case, the variable 'wordInput' has the reference to the input element. To get its value, you need to do
const wordInputValue = wordInput.value;
which returns the string entered in the input. Now to turn it into lower case, simply do
const wordInputValueLC = wordInput.value.toLowerCase();
Is it not this line that needs to change?
if(wordInput.value === currentWord.innerHTML) {
make it
if(wordInput.value.toLowerCase() === currentWord.innerHTML) {
and it should work since it is converting the entered word to lowercase and then comparing it to the target word.....

How to make this logic

I'm having a problem with this exercise
So far I have the boxes, but the logic in javascript I don't know how to do ? Any advise ?
this is my progress:
The code is really simple:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>David Aparicio</title>
</head>
<body>
<div class="container">
<div class="box active">
</div>
<div class="box">
</div>
<div class="box">
</div>
</div>
<div class="buttons">
<button> Left </button>
<button> Right </button>
</div>
Here's my take on it.
First I added ids to your buttons to reference them.
<div class="buttons">
<button id="left"> Left </button>
<button id="right"> Right </button>
</div>
Then my javascript looks like this:
//Find all boxes and put them in an array
let boxes = document.querySelectorAll(".box");
let activeIndex = 0;
function changeActive() {
//remove previous active class
document.querySelector(".active").classList.remove("active");
//find box at active index and add active class
document.querySelectorAll(".box")[activeIndex].classList.add("active");
}
//Event listeners to increment and decrement the active index
document.getElementById("left").addEventListener("click", function() {
if(activeIndex > 0) {
activeIndex -= 1;
changeActive();
}
});
document.getElementById("right").addEventListener("click", function() {
if(activeIndex < boxes.length -1) {
activeIndex += 1;
changeActive();
}
});
JSFiddle: https://jsfiddle.net/r6foyj1d/13/

Categories

Resources