How to make this logic - javascript

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/

Related

Increasing a progress bar by clicking a button

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>

Implement nav dots to my slider to match with my div element

https://jsfiddle.net/R0bert0M3/uc8kntes
<html>
<link href="./style.css" rel="stylesheet" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="divs">
<div class="cls1">
<div>Yes 1 </div>
<div>Element 1 </div>
</div>
<div class="cls2">
<div>Yes 2 </div>
<div>Element 2 </div>
</div>
<div class="cls3">
<div>Yes 3 </div>
<div>Element 3 </div>
</div>
</div>
<a id="next">next</a>
<a id="prev">prev</a>
<br>
<br>
<br>
<br>
<li class="nav-dots">
<label class="nav-dot" id="img-dot-1" onclick=""></label>
<label class="nav-dot" id="img-dot-2"></label>
<label class="nav-dot" id="img-dot-3"></label>
</li>
<script>
$(document).ready(function(){
$(".divs>div").each(function(e) {
if (e != 0)
$(this).hide();
});
$("#next").click(function(){
const visibleDiv = $(".divs>div:visible");
const nextDiv = visibleDiv.next();
if(nextDiv.length > 0) {
visibleDiv.hide();
nextDiv.show();
}
});
$("#prev").click(function(){
const visibleDiv = $(".divs>div:visible");
const prevDiv = visibleDiv.prev();
if(prevDiv.length > 0) {
visibleDiv.hide();
prevDiv.show();
}
});
});
</script>
</html>
When I click next I want it to match with the dots, and when I click the dots I want my slides to also change. The CSS is in the jsfiddle link.I tried to use OnClick but I couldn't figure it out how to do it .is there any way to make this work.
Find a working example at this fiddle: https://jsfiddle.net/mg0u85sq/
To get the dots to match the current slide shown I have used a class .nav-dot--active to provide the styles. This is set initially on the first dot, and then set inside the selectSlide function.
To enable the dots to select a slide, we can use button elements and aria-label attribute to provide better accessibility support.
You can hook up the click events with something along the lines of:
$(".nav-dot").each((index) => {
$(this).click(() => {
selectSlide(index);
});
});

Changing simultaneously text and image on slider

I made a slider with a series of images. I created two buttons (prev and next) that allow browsing the images.
I created also two divs where I put the slide's number and title.
My goal is to change the image, number, and title of the slide simultaneously each time a click event on prev or next buttons occurs.
I have started programming some months ago and I am having difficulties associating images with corresponding titles and numbers.
Could someone help me complete my code?
Actually, the following code works for me to show the image on click but is not complete.
I would like to change all the elements (image, title and number) at the same time after click.
More details on the picture:Screen of the homepage
// Carousel
let sliderImage = document.querySelector(".sliderImage");
let images = [
"carousel1.jpg",
"carousel2.jpg",
"carousel3.jpg",
"carousel4.jpg",
"carousel5.jpg",
"carousel6.jpg",
"carousel7.jpg",
];
let i = 0; // Current image index
// I have already created in html file 2 btns with "onclick" event
// that trigger the following functions:
function prev() {
if (i <= 0) i = images.length;
i--;
return getSlideImg();
}
function next() {
if (i >= images.length - 1) i = -1;
i++;
return getSlideImg();
}
function getSlideImg() {
return sliderImage.setAttribute("src", "img/" + images[i]);
}
<!-- Carousel -->
<div class="carousel-container">
<div class="carousel-slide">
<img src="./img/carousel1.jpg" alt="" class="sliderImage"/>
<!-- Carousel card -->
<div class="carousel__card-container">
<div class="carousel__card-title">Soggiorno</div>
<div class="carousel__slide-data">
<div class="slide__number">01</div>
<div class="slide__loader">
<div class="loader__line-grey">
<div class="loader__line-white"></div>
</div>
</div>
</div>
</div>
<!-- Carousel buttons -->
<div class="carousel-btn">
<a href="#" class="button left-arrow bottone" id="prevBtn" onclick="prev()">
<i class="ri-arrow-left-s-line btn-icon-small"></i>
</a>
<a href="#" class="button right-arrow bottone" id="nextBtn" onclick="next()">
<i class="ri-arrow-right-s-line btn-icon-small"></i>
</a>
</div>
</div>
</div>
set all values inside getSlideImg function so everything will update with corresponding image
// Carousel
let sliderImage = document.querySelector(".sliderImage"),
container = document.querySelector(".carousel-container")
let images = [
"carousel1.jpg",
"carousel2.jpg",
"carousel3.jpg",
"carousel4.jpg",
"carousel5.jpg",
"carousel6.jpg",
"carousel7.jpg",
];
let i = 0; // Current image index
// I have already created in html file 2 btns with "onclick" event
// that trigger the following functions:
function prev() {
if (i <= 0) i = images.length;
i--;
return getSlideImg();
}
function next() {
if (i >= images.length - 1) i = -1;
i++;
return getSlideImg();
}
function getSlideImg() {
container.querySelector(".slide__number").innerText = i + 1
container.querySelector(".carousel__card-title").innerText = images[i]
return sliderImage.setAttribute("src", "img/" + images[i]);
}
// for onload
getSlideImg()
<!-- Carousel -->
<div class="carousel-container">
<div class="carousel-slide">
<img src="./img/carousel1.jpg" alt="" class="sliderImage"/>
<!-- Carousel card -->
<div class="carousel__card-container">
<div class="carousel__card-title">Soggiorno</div>
<div class="carousel__slide-data">
<div class="slide__number">01</div>
<div class="slide__loader">
<div class="loader__line-grey">
<div class="loader__line-white"></div>
</div>
</div>
</div>
</div>
<!-- Carousel buttons -->
<div class="carousel-btn">
<a href="#" class="button left-arrow bottone" id="prevBtn" onclick="prev()">
<i class="ri-arrow-left-s-line btn-icon-small">prev</i>
</a>
<a href="#" class="button right-arrow bottone" id="nextBtn" onclick="next()">
<i class="ri-arrow-right-s-line btn-icon-small">next</i>
</a>
</div>
</div>
</div>

How to get number of div left after deleting?

In my HTML there are eight div. I was able to get the number of the div using jQuery and insert it into the .num div element.
However when I delete one of the div by clicking the delete button, the number of divs in the span retrieved through jQuery won't update to the current number of divs remaining. It will still show 8.
How can I get the current number of div elements left in the DOM immediately after clicking the button?
setTimeout(() => {
if ($(".delete div").length > 0) {
$(".num span").html($(".delete div").length);
}
}, 100);
$("button").click(function() {
$(".delete div:last-child").remove();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
```
<div class="delete">
<div class="div1">1</div>
<div class="div2">2</div>
<div class="div3">3</div>
<div class="div4">4</div>
<div class="div5">5</div>
<div class="div6">6</div>
<div class="div7">7</div>
<div class="div8">8</div>
</div>
<div class="num">Number of div: <span>0</span></div><br>
<button>delete</button>
The problem is because you're using setTimeout(), which only runs once after the specified delay.
For the pattern you're using to work you need to use setInterval() instead, which will run repeatedly at the set delay:
setInterval(() => {
if ($(".delete div").length > 0) {
$(".num span").html($(".delete div").length);
}
}, 100);
$("button").click(function() {
$(".delete div:last-child").remove();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="delete">
<div class="div1">1</div>
<div class="div2">2</div>
<div class="div3">3</div>
<div class="div4">4</div>
<div class="div5">5</div>
<div class="div6">6</div>
<div class="div7">7</div>
<div class="div8">8</div>
</div>
<div class="num">Number of div: <span>0</span></div><br>
<button>delete</button>
However, using a timer for this is not ideal. As the number of div elements is only affected when the button is clicked, just update the .num span element in that event handler:
var $span = $(".num span").html($(".delete div").length);
$("button").click(function() {
$(".delete div:last-child").remove();
$span.html($(".delete div").length);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="delete">
<div class="div1">1</div>
<div class="div2">2</div>
<div class="div3">3</div>
<div class="div4">4</div>
<div class="div5">5</div>
<div class="div6">6</div>
<div class="div7">7</div>
<div class="div8">8</div>
</div>
<div class="num">Number of div: <span>0</span></div><br>
<button>delete</button>

Toggle multiple classes

I'm stuck with a menu I'd love to add to my website.
I have branched my work in:
Commercial
Fashion
Music
Portrait
So I have a menu like this one above.
When I click on one section, let's say "Commercial" I want all the others to be display:none.
Have a look at this FIDDLE: http://jsfiddle.net/bfevLsj2/8/
$(document).ready(function() {
$("#commercial").click(function() {
$(".commercial").toggleClass("show");
$(".fashion").toggleClass("hid");
$(".music").toggleClass("hid");
$(".portrait").toggleClass("hid");
});
});
You need siblings() width jquery
Description: Get the siblings of each element in the set of matched elements, optionally filtered by a selector.
$("[id]").click(function(){ //onclick on element with ID
var selected = $(this).attr("id"); // save the value of that ID
$("."+ selected).show().siblings("[class]").hide()//find the class with the same value as class and show it then find all siblings class and hide them
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="commercial">Commercial</div>
<div id="fashion">Fashion</div>
<div id="music">Music</div>
<div id="portrait">Portrait</div><br />
<div class="commercial">C</div>
<div class="fashion">F</div>
<div class="music">M</div>
<div class="portrait">P</div>
BUT a better approach would be to use data-*
$("[data-tab]").click(function(){
var current = $(this).attr("data-tab");
$("[data-content="+ current +"]").show().siblings("[data-content]").hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div data-tab="commercial">Commercial</div>
<div data-tab="fashion">Fashion</div>
<div data-tab="music">Music</div>
<div data-tab="portrait">Portrait</div><br />
<div data-content="commercial">C</div>
<div data-content="fashion">F</div>
<div data-content="music">M</div>
<div data-content="portrait">P</div>
AGAIN it is better to use pure javascript
function runClick (event) {
var current = this.getAttribute("data-tab");
for( var content = 0; content < dataContent.length; content++) {
dataContent[content].style.display = "none"
}
document.querySelector("[data-content="+ current + "]").style.display = "block"
}
var dataTabs = document.querySelectorAll("div[data-tab]"),
dataContent = document.querySelectorAll("div[data-content]");
for(var tab = 0; tab < dataTabs.length; tab++){
dataTabs[tab].addEventListener("click", runClick , false);
}
<div data-tab="commercial">Commercial</div>
<div data-tab="fashion">Fashion</div>
<div data-tab="music">Music</div>
<div data-tab="portrait">Portrait</div><br />
<div data-content="commercial">C</div>
<div data-content="fashion">F</div>
<div data-content="music">M</div>
<div data-content="portrait">P</div>
HTML:
<div id="commercial" class="menuItem">Commercial</div>
<div id="fashion" class="menuItem">Fashion</div>
<div id="music" class="menuItem">Music</div>
<div id="portrait" class="menuItem">Portrait</div><br />
<div class="commercial content">C</div>
<div class="fashion content">F</div>
<div class="music content">M</div>
<div class="portrait content">P</div>
JavaScript:
$(document).ready(function(){
$(".menuItem").click(function(){
var id = this.id;
$('.content').removeClass('show').addClass('hid');
$('.'+id).addClass('show').removeClass('hid');
});
});
CSS:
.hid {
display:none;
}
.show {
display:block;
}
Fiddle
Have a look at this fiddle, think it's what you want
Essentially you can use .toggle() to traverse and show/hide according to whether it's the one you want to show.
$(function(){
// find all the links that you can click
$("div.clickable a").click(function(e) {
// when they're clicked, find the identifier of
// the tab/div you want shown
var clickedId = $(e.target).parent("div").attr("id");
// traverse all of the divs and show/hide according
// to whether it's the tab you want
$("div.section").each(function(index, div) {
$(div).toggle($(div).hasClass(clickedId));
});
});
});
And the HTML:
<div id="commercial" class="clickable">Commercial</div>
<div id="fashion" class="clickable">Fashion</div>
<div id="music" class="clickable">Music</div>
<div id="portrait" class="clickable">Portrait</div>
<br />
<div class="commercial section">C</div>
<div class="fashion section">F</div>
<div class="music section">M</div>
<div class="portrait section">P</div>
HTH
Edited to add an "ALL" link in this fiddle
$("div.clickable a").click(function(e) {
// when they're clicked, find the identifier of
// the tab/div you want shown
var clickedId = $(e.target).parent("div").attr("id");
// traverse all of the divs and show/hide according
// to whether it's the tab you want
$("div.section").each(function(index, div) {
$(div).toggle($(div).hasClass(clickedId) || clickedId=="ALL");
});
});
After adding this to the list of clickable divs:
<div id="ALL" class="clickable">
ALL
</div>
Your could that more easy like:
<div class="link" id="commercial">Commercial</div>
<div class="link" id="fashion">Fashion</div>
<div class="link" id="music">Music</div>
<div class="link" id="portrait">Portrait</div><br />
<div class="commercial elem">C</div>
<div class="fashion elem">F</div>
<div class="music elem">M</div>
<div class="portrait elem">P</div>
<script type="text/javascript">
$(document).ready(function(){
$(".link").click(function(){
var id = $(this).attr('id');
$('.elem').hide();
$('.' + id).show();
});
});
</script>

Categories

Resources