BEGINNER: Removing items from Javascript Array - javascript

I am coding a random quote generator. I almost have it fully coded how I want. I am a beginner in HTML and I've never used Javascript before this weekend. I took from multiple tutorials to code this exactly how I want it and am very proud. I have one last thing I am trying to do. When a item from the array is called, I want it to be removed, stored in another array and when the original array reaches 0, I want it to reset. I know its possible but I am not sure what to add to this script to make it work. Thanks so much for any help.
const quotes = [{
game: 'CARD TYPE 1',
quote: "This is the card description for Card Type 1",
rule: "Card Type 1 Rules"
},
{
game: 'CARD TYPE 2',
quote: "This is the card description for Card Type 2",
rule: "Card Type 2 Rules"
},
{
game: 'CARD TYPE 3',
quote: "This is the card description for Card Type 3",
rule: "Card Type 3 Rules"
}
];
const maincontainer = document.querySelector("#quoteBtn");
const questionStyle = document.querySelector("#quote");
const gameTitleStyle = document.querySelector("#gameTitle");
const ruleStyle = document.querySelector("#ruleTxt");
quoteBtn.addEventListener("click", displayQuote);
function displayQuote() {
let number = Math.floor(Math.random() * quotes.length);
gameTitle.innerHTML = quotes[number].game;
quote.innerHTML = quotes[number].quote;
ruleTxt.innerHTML = quotes[number].rule;
}
<style type="text/css">
body {
font-family: "Poppins", sans-serif;
background-color: #3F6BFF;
}
.maincontainer {
position: relative;
width: 500px;
height: 300px;
animation: flip 1s;
text-align: center;
margin: 0 auto;
border-radius: 25px;
}
.thecard {
position: relative;
width: 100%;
height: 100%;
transform-style: preserve-3d;
transition: all 0.5s ease;
border-radius: 25px;
}
.thecard:active {
transform: rotateY(360deg);
}
.thefront {
position: absolute;
width: 100%;
height: 100%;
padding-right: 30px;
padding-left: 30px;
backface-visibility: hidden;
background-color: #fff;
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
border-radius: 25px;
}
.theback {
position: absolute;
width: 100%;
height: 100%;
padding-right: 30px;
padding-left: 30px;
backface-visibility: hidden;
transform: rotateY(180deg);
background: #000;
border-radius: 25px;
}
.gameTitleStyle {
font-weight: 800;
font-size: 32px;
text-transform: uppercase;
}
.ruleStyle {
position: relative;
top: -20px;
font-style: italic;
}
.questionStyle {
position: relative;
top: 20px;
font-size: 18px;
}
</style>
<body>
<div class="maincontainer" id="quoteBtn">
<div class="thecard">
<div class="thefront">
<h1 class="gameTitleStyle" id="gameTitle">Business Name</h1>
<p class="ruleStyle" id="ruleTxt">Rules</p>
<p class="questionStyle" id="quote">Card Description</p>
</div>
<div class="theback"></div>
</div>
</div>
</body>

Removing an element from an array can be done with the Array.prototype.splice() method. For example, this removes element 2 from an array called "items", and returns the removed element in a new array:
let removedItems = items.splice(2);
Add items to an array using Array.prototype.push():
otherArray.push(...removedItems);
The ...removedItems converts the removedItems array to a list of items. The ... is called the spread operator.
These should be enough to accomplish what you want.

Related

Modal stops working after image changes on page

Im building an app where you can like and dislike movies. I have a database of movies and show each one to the user. When you click like or dislike it takes you to the next poster.
I also have access to the description and rating. I've added my own modal to show the user when clicked more information on that movie.
The problem Im having is the modal works for the first movie and changes the class to active. However on the second one it stops working. I can see in the inspector the modal code is there and has the correct information for that movie. But the modal seems to still not work/become unresponsive. Perhaps its an error that I've missed. I notice that it does add active once again on the first item. Perhaps I need to find a way to switch to the current movie instead or incorporate the modal into the slides more? or find a way to reset it..
EDIT -:
Adding to the above. Having done a bit more testing. It seems like the modal doesnt know what id the slide is on.. So it never knows when the slide is changed.. Any ideas how I would do this?
EDIT2 -:
I've now got it so every modal has a unique id per poster using the contact.id. Any way to link the modal id together with the slides so when I change the slide the modal knows and changes to active on the next slide?
const modalBtn = document.querySelectorAll(".modal-btn");
const modalBg = document.querySelectorAll("movie-modal");
const modalClose = document.querySelectorAll(".close-button");
const overlay = document.querySelectorAll("overlay");
const overlayClose = document.querySelectorAll("overlay");
const activeModal = document.querySelectorAll(".movie-modal:first-child")
modalBtn.forEach(function(btn, index){
btn.addEventListener('click', function(click) {
console.log(click)
modalBg.classList.add('active');
overlay.classList.add('active');
var content_id = activeModal.data("id");
console.log(content_id)
});
});
modalClose.forEach(function(btn, index){
btn.addEventListener('click', function(click) {
console.log(click)
modalBg.classList.remove('active');
overlay.classList.remove('active');
});
});
overlay.forEach(function(overlay, index){
overlay.addEventListener('click', function() {
overlayClose.classList.remove('active');
});
});
overlay.forEach(function(overlay, index){
overlay.addEventListener('click', function() {
const modals = document.querySelectorAll('.movie-modal.active')
modals.forEach(modal => {
modal.classList.remove('active');
overlay.classList.remove('active');
})
})
});
$(function(){
var $activeSlide = $('#slides .slide:first-child');
// show first slide
$activeSlide.addClass("active");
// on click event decline
$("#decline").on("click", function(){
goToSlide('decline');
});
// on click approve then what?
$("#approve").on("click", function(){
var content_id = $activeSlide.data("id");
console.log(content_id)
goToSlide('approve');
// $.ajax({
// url: "/user_contents/liked" + content_id,
// method: "post",
// dataType: "ajax"
// });
});
// adding the 'showing' or 'active' slide class to each element
function goToSlide(action) {
$activeSlide.removeClass("active");
$activeSlide = $activeSlide.next(".slide");
// send data to controller
if(action == "approve"){
console.log(action);
} else {
console.log('dislike');
}
$activeSlide.addClass("active");
}
});
.movie-modal {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%) scale(0);
transition: 200ms ease-in-out;
box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px;
border-radius: 10px;
z-index: 10;
background-color: white;
width: 300px;
max-width: 80%;
color: black;
}
.movie-modal.active{
transform: translate(-50%, -50%) scale(1);
}
.movie-modal-header {
padding: 8px 16px;
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 1px solid rgb(182, 182, 182);
}
.movie-rating {
font-size: 1.25rem;
font-weight: bold;
}
.close-button {
cursor: pointer;
border: none;
outline: none;
background: none;
font-size: 1.25rem;
font-weight: bold;
}
.movie-modal-body {
padding: 16px;
color: rgb(160, 160, 160);
}
#overlay {
position: fixed;
opacity: 0;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.35);
pointer-events: none;
transition: 200ms ease-in-out;
}
#overlay.active {
opacity: 1;
pointer-events: all;
}
#slides {
position: relative;
height: 100%;
padding: 0px;
margin: 0 auto;
list-style-type: none;
}
.slide {
position: absolute;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
opacity: 0;
z-index: 1;
box-sizing: border-box;
color: #fff;
-webkit-transition: opacity 1s;
-moz-transition: opacity 1s;
-o-transition: opacity 1s;
transition: opacity 1s;
}
.showing {
opacity: 1;
z-index: 2;
}
#slide-controls {
margin: 20px 0 400px;
width: 100%;
position: absolute;
display: flex;
justify-content: center;
justify-content: space-between;
z-index: 10;
color: #ffffffba;
font-size: 24px;
top: 50%;
}
.image-carousel {
width: 100%;
height: 642px;
margin: 0 auto;
background-size: contain;
background-repeat: no-repeat;
position: relative;
}
#decline {
margin-left: 16px;
}
#approve {
margin-right: 16px;
}
.img-thumbnail {
padding: 0 !important;
}
<ul id="slides">
<% #contents.each_with_index do |content, i| %>
<li class="slide <%= 'active' if i == 0 %>" data-id="<%= content.id %>">
<div class="image-carousel" style="background-image: url('<%= content.poster %>')">
</div>
<button class="modal-btn">Open Modal</button>
<div id="movie-modal <%= content.id %>" class="movie-modal">
<div class="movie-modal-header">
<div class="movie-rating" style="">Average rating: <strong><%= content.rating %></strong></div>
<button class="close-button">×</button>
</div>
<div class="movie-modal-body"><p><%= content.description %></p></div>
</div>
<div id="overlay <%= content.id %>"></div>
</li>
<% end %>
</ul>
<div id="slide-controls">
<span id="decline"><i class="fa fa-solid fa-thumbs-down fa-2x"></i></span>
<span id="approve"><i class="fa fa-solid fa-thumbs-up fa-2x"></i></span>
</div>
This shows when the first poster is clicked the modal works and movie-modal active is added to the modal class
The second image with Morbius in it.. The modal class doesnt change for the current slide showing however it changes for the previous slide.. BUT the previous slide only changes once and then sticks to active. Nothing is shown on the poster.

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.

How to make a semi circle chart in react?

I am having a data like,
{
"initial": {
"unit": "GB",
"value": 2
},
"remaining": {
"unit": "GB",
"value": 0.2
},
"type": "Internet",
}
Where the initial value is total gb of mobile data and remaining consists of the remaining data available.
Requirement:
My requirement is like the below image,
I have tried with pure HTML and CSS like here, But issue here is that everything is hard coded .. So if we have some percentage then we need to adjust the css class .sc-percentage accordingly
body { background-color:#555888; font-family:sans-serif; color:#fff; text-align:center }
code { display:inline-block; max-width:600px; padding:80px 0 0; line-height:1.5; font-family:monospace; color:#ccc }
.sc-gauge { width:200px; height:200px; margin:200px auto; }
.sc-background { position:relative; height:100px; margin-bottom:10px; background-color:#fff; border-radius:150px 150px 0 0; overflow:hidden; text-align:center; }
.sc-mask { position:absolute; top:20px; right:20px; left:20px; height:80px; background-color:#555888; border-radius:150px 150px 0 0 }
.sc-percentage { position:absolute; top:100px; left:-200%; width:400%; height:400%; margin-left:100px; background-color:#00aeef; }
.sc-percentage { transform:rotate(25deg); transform-origin:top center; }
.sc-min { float:left; }
.sc-max { float:right; }
.sc-value { position:absolute; top:50%; left:0; width:100%; font-size:48px; font-weight:700 }
<code>
To change the current value of the Gauge, you need to change 88 to something else in HTML section and update the .sc-percentage rotate value from 158deg to something else.
This will be a part of the Simple Chart library.
</code>
<div class="sc-gauge">
<div class="sc-background">
<div class="sc-percentage"></div>
<div class="sc-mask"></div>
<span class="sc-value">0.2</span>
</div>
<span class="sc-min">0</span>
<span class="sc-max">2</span>
</div>
I would like to form a chart exactly as like given in the above image.
I am open to implement any kind of library like chartjs, d3, apex etc.., that supports this feature of having semi circle..
As I am a beginner with this scenario, kindly help me to resolve the feature as I am stuck for very long time with this.
A big thanks in advance..
React component:
const data = {
"initial": {
"unit": "GB",
"value": 2
},
"remaining": {
"unit": "GB",
"value": 0.9
},
"type": "Internet",
};
function SemiCircleChart({min, max, value}){
const angle = (value / max) * 180;
const style = {'--angle': angle + 'deg'};
return (
<div class="sc-gauge">
<div class="sc-background">
<div class="sc-percentage" style={style}></div>
<div class="sc-mask"></div>
<span class="sc-value">{ value }</span>
</div>
<span class="sc-min">{ min }</span>
<span class="sc-max">{ max }</span>
</div>)
}
ReactDOM.render(
<SemiCircleChart
min={0}
max={data.initial.value}
value={data.remaining.value}
/>,
document.querySelector('#app')
);
:root {
--angle: 90deg;
}
body {
background-color: #555888;
font-family: sans-serif;
color: #fff;
text-align: center
}
code {
display: inline-block;
max-width: 600px;
padding: 0;
line-height: 1.5;
font-family: monospace;
color: #ccc
}
.sc-gauge {
width: 200px;
height: auto;
margin: 20px auto;
}
.sc-background {
position: relative;
height: 100px;
margin-bottom: 10px;
background-color: #fff;
border-radius: 150px 150px 0 0;
overflow: hidden;
text-align: center;
}
.sc-mask {
position: absolute;
top: 20px;
right: 20px;
left: 20px;
height: 80px;
background-color: #555888;
border-radius: 150px 150px 0 0
}
.sc-percentage {
position: absolute;
top: 100px;
left: -200%;
width: 400%;
height: 400%;
margin-left: 100px;
background-color: #00aeef;
}
.sc-percentage {
transform: rotate(var(--angle));
transform-origin: top center;
}
.sc-min {
float: left;
}
.sc-max {
float: right;
}
.sc-value {
position: absolute;
top: 50%;
left: 0;
width: 100%;
font-size: 48px;
font-weight: 700
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<code>
This will be a part of the Simple Chart library.
</code>
<div id="app"></div>
Old answer:
You just need to use a CSS variable:
Declare a variable like:
:root{
--angle: 90deg;
}
and use it like:
.sc-percentage {
transform: rotate(var(--angle));
transform-origin: top center;
}
You can update this variable as style attribute from JavaScript:
element.style.setProperty("--angle", '180deg');
180deg would be full arc.
Here's an example with animation: https://codesandbox.io/s/angry-moon-t08hp?file=/src/App.js
You can set style variables in React, which is what this Codesandbox does:
<div
class="sc-percentage"
style={{ transform: `rotate(${(percent / 100) * 180}deg)` }}
></div>
And it uses a setInterval to toggle the percent.
The animation between the two percents is achieved simply with a CSS transition property:
.sc-percentage {
transform: rotate(25deg);
transition: transform 1s;
transform-origin: top center;
}

Chaining button clicks with jQuery

I'm trying to build a simple website that let's you click 6 different buttons. Each click of the button is supposed to trigger the display of specific content (as an img file). Clicking each of the six buttons should lead to different content. I have managed to achieve this part via Javascript getElementById.
However, to add a bit more complexity, I want to implement sequential decision making. Meaning that clicking Button "1" and THEN clicking Button "2" (or 3-6 for that matter) should each lead to the display of other specific content. Likewise clicking Button "1", then "2" and then "1" again should also display specific content. My sequential decision making is supposed to be limited to only two buttons interacting until the end of the decision is reached. So essentially, something like 1 -> 2 -> 3 can not happen, but 3 -> 6 -> 3 can happen. I hope it's not too complicated what I'm trying to do.
Anyway, here's some code I wrote trying to achieve this, but I'm fairly sure that my toggle function is not the correct way to go about it as I'm essentially simply placing pictures above each other and there is no sequency to any of the decisions made. I think to achieve this, I would need to chain the clicks, but I'm completely lost as to how to achieve that. Any help is greatly appreciated.
a:link {
color: white;
text-decoration: none;
}
a:visited {
color: white;
text-decoration: none;
}
a:hover {
color: white;
text-decoration: none;
}
a:active {
color: white;
text-decoration: none;
}
a.pos:link {
color: black;
text-decoration: none;
}
a.pos:visited {
color: black;
text-decoration: none;
}
a.pos:hover {
color: white;
text-decoration: none;
}
a.pos:active {
color: black;
text-decoration: none;
}
a.button:link, a.button:visited {
margin: auto;
position: absolute;
top: 0px;
left: 0px;
background-color: yellowgreen;
width: 345px;
line-height: 20px;
height: 185px;
border: 2px solid;
border-color: white;
text-align: center;
border-radius: 100px;
font-family: open sans;
font-size: 9px;
color: black;
font-weight: 650;
color: white;
padding: 14px 25px;
text-align: center;
text-decoration: none;
display: inline-block;
}
a.button:hover, a.button:active {
background-color: yellowgreen;
}
body {margin:0;}
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333;
position: fixed;
top: 0;
width: 100%;
}
li {
float: left;
}
li a {
display: block;
color: white;
text-align: center;
padding: 20px 30px;
font-family: open sans;
text-decoration: none;
}
li a:hover:not(.active) {
background-color: #111;
}
.active {
background-color: #4CAF50;
}
h1 {
color: whitesmoke;
font-family: open sans;
font-size: 300%;
}
.table {
margin: auto;
position: relative;
width: 450px;
top: -1350px;
border: 6px solid #333333;
border-radius: 250px;
background: #737373;
padding-top: 150px;
padding-right: 50px;
padding-left: 50px;
padding-bottom: 150px;
}
#quattro {
margin: auto;
position: absolute;
bottom: -25px;
right: 250px;
background-color: gold;
width: 50px;
line-height: 50px;
height: 50px;
border: 1px solid black;
text-align: center;
border-radius: 50px;
font-family: open sans;
font-size: 20px;
font-weight: 650;
}
#uno {
margin: auto;
position: absolute;
top: -25px;
right: 250px;
background-color: gold;
width: 50px;
line-height: 50px;
height: 50px;
border: 1px solid black;
text-align: center;
border-radius: 50px;
font-family: open sans;
font-size: 20px;
font-weight: 650;
}
#duo {
margin: auto;
position: absolute;
top: 25px;
right: 10px;
background-color: gold;
width: 50px;
line-height: 50px;
height: 50px;
border: 1px solid black;
text-align: center;
border-radius: 50px;
font-family: open sans;
font-size: 20px;
font-weight: 650;
}
#tres {
margin: auto;
position: absolute;
bottom: 25px;
right: 10px;
background-color: gold;
width: 50px;
line-height: 50px;
height: 50px;
border: 1px solid black;
text-align: center;
border-radius: 50px;
font-family: open sans;
font-size: 20px;
font-weight: 650;
}
#cinqo {
margin: auto;
position: absolute;
bottom: 25px;
left: 10px;
background-color: gold;
width: 50px;
line-height: 50px;
height: 50px;
border: 1px solid black;
text-align: center;
border-radius: 50px;
font-family: open sans;
font-size: 20px;
font-weight: 650;
}
#seis {
margin: auto;
position: absolute;
top: 25px;
left: 10px;
background-color: gold;
width: 50px;
line-height: 50px;
height: 50px;
border: 1px solid black;
text-align: center;
border-radius: 50px;
font-family: open sans;
font-size: 20px;
font-weight: 650;
}
.imgrange1 {
text-align: center;
color: white;
position: absolute;
top: 400px;
left: -400px;
}
.imgrange2 {
text-align: center;
color: white;
position: absolute;
top: 400px;
left: 320px;
}
.centered {
font-family: open sans;
font-size: 150%;
position: absolute;
top: -3%;
left: 50%;
transform: translate(-50%, -50%);
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="css/style.css">
<style>
.myimgdivtoggle1 {
display: none;
}
.myimgdivtoggle2 {
display: none;
}
.myimgdivtoggle3 {
display: none;
}
.myimgdivtoggle4 {
display: none;
}
.myimgdivtoggle5 {
display: none;
}
</style>
<script>
$(document).ready(function(){
$('.togglebtn1').click(function(){
$('.myimgdivtoggle1').toggle();
});
});
$(document).ready(function(){
$('.togglebtn2').click(function(){
$('.myimgdivtoggle2').toggle();
});
});
$(document).ready(function(){
$('.togglebtn3').click(function(){
$('.myimgdivtoggle3').toggle();
});
});
$(document).ready(function(){
$('.togglebtn4').click(function(){
$('.myimgdivtoggle4').toggle();
});
});
$(document).ready(function(){
$('.togglebtn5').click(function(){
$('.myimgdivtoggle5').toggle();
});
});
$(document).ready(function(){
$('.togglebtn6').click(function(){
$('.myimgdivtoggle6').toggle();
});
});
</script>
</head>
<body>
<ul>
<li><a class="active" href="index.html">Main</a></li>
<li>News</li>
<li>Contact</li>
<li>About</li>
</ul>
<div style="padding:20px;margin-top:30px;background-color:cadetblue;height:1500px;">
<h1><center>TEST</center></h1>
</div>
<div class="table">
<button type="button" class="togglebtn1" id="uno">1</button>
<div class="myimgdivtoggle1">
<img src="1.JPG" class="imgrange1"/>
</div>
<button type="button" class="togglebtn2" id="duo">2</button>
<div class="myimgdivtoggle2">
<img src="2.JPG" class="imgrange1"/>
</div>
<button type="button" class="togglebtn3" id="tres">3</button>
<div class="myimgdivtoggle3">
<img src="3.JPG" class="imgrange1"/>
</div>
<button type="button" class="togglebtn4" id="quattro">4</button>
<div class="myimgdivtoggle4">
<img src="4.JPG" class="imgrange1"/>
</div>
<button type="button" class="togglebtn5" id="cinqo">5</button>
<div class="myimgdivtoggle5">
<img src="5.JPG" class="imgrange1"/>
</div>
<button type="button" class="togglebtn6" id="seis">6</button>
<div class="myimgdivtoggle6">
<img src="6.JPG" class="imgrange1"/>
</div>
</body>
</html>
Though I can not provide you with a firm solution, I can however offer a small example which illustrates how to incorporate an array which tracks the buttons that have been clicked, as well as a way to get certain content from combinations of buttons.
Run the example and try the combinations 363, 254, 521 and 165 to get some results showing up. I've tried my best to show what the produced output is.
I'd suggest that you take a look at it and ask any questions if you have them. I'll check in to see if you do.
$(document).ready(function() {
/**
* Select the buttons.
* The $display and $clickedButtons are just to output
* the values that are stored.
*/
const $buttons = $('.button');
const $display = $('#display');
const $clickedButtons = $('#clicked-buttons');
const $removeButton = $('#remove-button');
/**
* Array which tracks your clicked buttons.
* If a button is clicked, the value of that button should be added to this array.
* The combination of the values will then later represent the key.
*/
const values = [];
/**
* This is where any know combinations are stored.
* The values in the values array will later be transformed into a single string to
* see if it matches any key in the combinations object below.
* If it does, it will give you a value, otherwise undefined.
*/
const combinations = {
"363": "https://www.fillmurray.com/200/200",
"254": "https://www.fillmurray.com/220/220",
"521": "https://www.fillmurray.com/240/240",
"165": "https://www.fillmurray.com/300/300"
};
/**
* Combines the values to form a single key and check if that key matches a combination.
* If there is a match the content should be anything other than undefined.
*/
function tryCombination() {
// This will output the current values from the array.
$clickedButtons.text(values);
// Transform the array into a single string.
// This will be the key to select content.
// ["1", "2", "3"] becomes "123".
const key = values.join('');
// Check if key has a match in the combinations object.
const url = combinations[key];
if (url !== undefined) {
// It does, show the content.
$display.attr('src', url);
$display.removeClass('hidden');
} else {
// It doesn't, empty the content.
$display.removeAttr('src');
$display.addClass('hidden');
}
}
/**
* Listen for the click event on all the buttons.
* When clicked, get the value of that clicked button and add that to the values array.
* It then calls the tryCombination function to evaluate if the values in the values
* array make a valid combination.
*/
$buttons.on('click', function() {
// This is the currently clicked button.
const $button = $(this);
// Get the value of the button.
const value = $button.val();
// If there already are 3 previously clicked buttons,
// then empty the array, so we can start a new combination.
if (values.length === 3) {
values.length = 0;
}
// Now add the newly clicked value.
values.push(value);
// Render and try the combination.
tryCombination();
});
/**
* Remove the last item in the values array.
* Then retry to create a valid combination.
*/
$removeButton.on('click', function() {
// Remove the last item from the values array
values.pop();
// Render and try the new combination.
tryCombination();
})
});
.container {
display: grid;
grid-template-rows: auto auto;
grid-template-columns: 200px 1fr;
grid-gap: 1em;
border: 1px solid #d0d0d0;
background-color: #f7f7f7;
padding: 1em;
border-radius: 5px;
}
.buttons {
grid-area: 1 / 1 / 2 / 3;
}
#display {
grid-area: 2 / 1 / 3 / 2;
width: 200px;
height: 200px;
background-color: #d0d0d0;
border-radius: 5px;
}
#clicked-buttons {
grid-area: 2 / 2 / 3 / 3;
display: block;
background-color: #d0d0d0;
border-radius: 5px;
padding: 1em;
margin: 0;
}
#remove-button {
grid-area: 1 / 2 / 2 / 3;
}
.hidden {
opacity: 0;
visibility: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="buttons">
<button class="button" id="1" value="1" >1</button>
<button class="button" id="2" value="2" >2</button>
<button class="button" id="3" value="3" >3</button>
<button class="button" id="4" value="4" >4</button>
<button class="button" id="5" value="5" >5</button>
<button class="button" id="6" value="6" >6</button>
</div>
<img id="display" class="hidden">
<button id="remove-button">Remove last input</button>
<code id="clicked-buttons"></code>
</div>
Edit
In the spirit of showing is better than telling; your last comment was about having a loose combination of numbers. This adds another layer of complexity.
Objects can only have keys that are strings (or Symbols) to get and set values. But in your case you'll want an array of numbers which represent the keys in any order, so plain objects are not suitable anymore.
The solution for this is the Map object. This object can have any type of key and value. So we can make a link between a combination of numbers and the images they represent (hence the name "map").
The example below uses this method. I've written a function that checks if an array of numbers is a match with any combination in the map. And if it does it return an array of images, referring to your previous comment.
Check it out. I believe this one to be more complex, so once more feel free to ask questions.
/**
* Create a Map instance.
*/
const combinations = new Map();
/**
* Values and keys are added with the set() method.
* This could still be improved with a loop setting each
* combination / images pair.
*/
combinations.set([3, 3, 6], ['https://www.fillmurray.com/200/200', 'https://www.fillmurray.com/200/200']);
combinations.set([2, 4, 5], ['https://www.fillmurray.com/220/220', 'https://www.fillmurray.com/220/220']);
combinations.set([1, 2, 5], ['https://www.fillmurray.com/240/240']);
combinations.set([1, 5, 6], ['https://www.fillmurray.com/300/300', 'https://www.fillmurray.com/300/300', 'https://www.fillmurray.com/300/300']);
const tryCombination = (key, combinations) => {
/**
* Loop over every combination.
* [combination, images] exposes the key-value pair,
* it's just a syntax to write fewer lines
*/
for (const [combination, images] of combinations) {
/**
* Create an array for the matches. If a number of the
* combination is in the given key, then that number
* will be pushed to the matches list. In the end,
* if everything matches, we should have just as many
* matches as numbers in the combination. That way
* we know if a key is correct.
*/
const matches = [];
/**
* We'll do some manipulation on the combination array,
* so to keep it intact we make a copy and manipulate that instead.
*/
const combinationCopy = Array.from(combination);
/**
* Count backwards through the combination array.
* Backwards counting is necessary when you remove items
* from the array while looping. I'd suggest you look
* into that subject.
*/
for (let i = combinationCopy.length - 1; i >= 0; i--) {
/**
* Get the current number we're looping over.
*/
const number = combinationCopy[i];
/**
* If that number is in the key array..
*/
if (key.includes(number)) {
/**
* ..then push that number to the matches array..
*/
matches.push(number);
/**
* ..and remove it from the copied combination array.
* We do this to prevent duplicate hits for cases
* where you have multiple occurrences of the same number,
* like [3, 3, 6]. When the first 3 hits, it will be removed.
* Then we have [3, 6] and we know we only need one more
* 3 and a 6.
*/
combinationCopy.splice(i, 1);
}
}
/**
* Now if every number has been matched correctly, then
* the amount of matches should be the same as the length
* of the combination. If that is the case, return the
* images. Otherwise, do nothing.
*/
if (matches.length === combination.length) {
return images;
}
}
/**
* If there are no matches, just return false, notifying the
* user that the combination is incorrect.
*/
return false;
};
console.log(tryCombination([5, 4, 2], combinations)); // Hit!
console.log(tryCombination([5, 1, 6], combinations)); // Hit!
console.log(tryCombination([2], combinations)); // Fail!
console.log(tryCombination([5, 4, 4], combinations)); // Fail!
console.log(tryCombination([3, 6, 3], combinations)); // Hit!

Custom / Styled prompt window?

I'm trying to make a 'Choose your Adventure' game, and I want to know if it's possible to make a styled/custom 'Prompt' window, and if it can be not opened up as a 'prompt' window, but have the prompt and user input in a selected HTML box? This is what I mean.
If my HTML has
HTML
<html>
<body>
<textarea class="prompt" disabled="1"></textarea><br>
<input class="input" type="text" value="inputText"></input>
<input type="submit" value="userInput"></input>
</body>
</html>
and CSS of
CSS
.prompt {
width: 300px;
height: 500px;
background: black;
color: #FFA500;
}
and JavaScript (I probably will mess up the code)
JavaScript
var prompt = document.getElementByClassName("prompt");
var choice = prompt("What is your choice? CHOICE1, CHOICE2, or CHOICE3?").toUpperCase();
prompt.innerHTML = choice;
and I hope to get something like the prompt not showing up a dialogue window but instead putting the prompt text into the textarea, and the user put in their choice with the input, then submit it by the submit button. How could I get it so that the prompt window instead outputs the question/text to the textarea, and the user puts in their answer via the input text field, and submitting it via the input submit button, and it works like normal. Is this even possible?
If not, is it at least possible to style the prompt dialogue box itself? Here's my code so far.
function fight() {
var intro = prompt("You are a hero who saved your town from a dragon attack years ago. You had fun murdering that dragon, but sadly no dragon has attacked since. Just when all hope is lo, you hear the sirens ring through the city. You know what that means. Do you PREPARE, or IGNORE THE SIRENS?").toUpperCase();
switch(intro) {
case 'PREPARE':
if(intro === "PREPARE") {
prompt("You decided to " + intro + ". You need to choose what you will do. Keep in mind, the more activities you do, the less energy you have! You only have 3 days to prepare! What do you do? Do you SEARCH ARMOR STAND, SEARCH WEAPON STAND, GO TO MERCHANT, FIGHT DRAGON, TRAIN, or SLEEP?").toUpperCase();
}
}
}
#import url(http://fonts.googleapis.com/css?family=Permanent+Marker);
html, body {
background: #000;
margin: 0;
padding: 0;
}
#wrap {
width: 760px;
margin-left: auto;
margin-right: auto;
}
.container {
position: relative;
top: 50px;
margin-left: auto;
margin-right: auto;
width: 570px;
height: 350px;
border: 6px ridge orange;
padding: 0;
}
.container img {
position: absolute;
bottom: 0px;
width: 570px;
height: 350px;
z-index: -1;
}
p.intro {
color: black;
text-shadow:
-1px -1px 0 #FFF,
1px -1px 0 #FFF,
-1px 1px 0 #FFF,
1px 1px 0 #FFF;
}
h2.header {
text-shadow:
-1px -1px 0 #FFA500,
1px -1px 0 #FFA500,
-1px 1px 0 #FFA500,
1px 1px 0 #FFA500;
}
.box {
float: left;
min-width: 567px;
min-height: 350px;
}
.box h2 {
font-family: 'Permanent Marker', cursive;
font-size: 200%;
text-align: center;
}
.box p {
font-family: 'Permanent Marker', arial;
text-align: center;
}
.box a {
position: absolute;
left: 165px;
display: inline-block;
border: 3px groove #000;
border-radius: 5px;
background: red;
margin-left: auto;
margin-right: auto;
width: 225px;
height: 75px;
font-family: 'Permanent Marker', cursive;
color: #FFA500;
text-shadow:
-1px -1px 0 #000,
1px -1px 0 #000,
-1px 1px 0 #000,
1px 1px 0 #000;
text-align: center;
}
.battles img {
}
<html>
<body>
<div id="wrap">
<div class="box">
<div class="container">
<h2 class="header">Dragon Slayer - REBORN!</h2>
<p class="intro">You are a hero who saved your town from a dragon attack years ago. You had fun murdering that dragon, but sadly no dragon has attacked since. Just when all hope is lost, you hear the sirens ring through the city. You know what that means.</p>
<br>BEGIN!
<img class="scenario" src="http://www.thegaminghideout.com/school/stage1.png">
<div class="battles">
</div>
</div>
</div>
</div>
</body>
</html>
Here is an example using jQuery. jQuery is useful for manipulating DOM elements. Instead of selecting an object by doing:
document.getElementById('someid');
You would select the element as you would in CSS:
$('#someid);
In my adventure game example, I used a JSON object to contain my story and its paths. The story object is a map of path id (e.g. 'intro', 'choose_weapon') to a scenario object. This helps to organize your story.
I used buttons instead of input fields for the options since making the user input their choices gets pretty annoying.
// Contains the story and paths
var story = {
intro: {
prompt: 'It is 12am and you are starving. It\'s too late to order delivery. You know what that means.',
options: [{
name: 'Fight',
path: 'choose_weapon'
}, {
name: 'Starve',
path: 'die_starve'
}]
},
choose_weapon: {
prompt: 'Choose your weapon!',
options: [{
name: 'Knife',
path: 'die_cut'
}, {
name: 'Toaster',
path: 'toast'
}]
},
toast: {
prompt: 'You toast some bread. What do you do next?',
options: [{
name: 'Eat it!',
path: 'eat'
}, {
name: 'Slather on some peanut butter!',
path: 'peanut_butter'
}]
},
peanut_butter: {
prompt: 'There is now peanut butter on your bread. Excellent choice. What do you do next?',
options: [{
name: 'Eat it!',
path: 'eat'
}, {
name: 'Throw it away',
path: 'die_starve'
}]
},
eat: {
prompt: 'It was delicious! You are no longer hungry.',
options: [{
name: 'Start Again',
path: 'intro'
}]
},
die_cut: {
prompt: 'You accidentally cut yourself and bleed to death.',
options: [{
name: 'Start Again',
path: 'intro'
}]
},
die_starve: {
prompt: 'You have died of hunger!',
options: [{
name: 'Start Again',
path: 'intro'
}]
}
}
/**
* Chosen option is an object with properties {name, path}
*/
function display_scenario(chosen_option) {
var option_name = chosen_option.name;
var option_path = chosen_option.path;
var scenario = story[option_path];
// Clear the #prompt div and the #options div
$('#prompt').empty();
$('#options').empty();
// Create a <p> to display what the user has chosen if option_name is not null and append it to the #prompt <div>
if (option_name) {
$('<p>').html('You have chosen <b>' + option_name + '</b>').appendTo('#prompt');
}
// Append the scenario's prompt
$('<p>').html(scenario.prompt).appendTo('#prompt');
// Append the options into the #options <div>
// We want to loop through all the options and create buttons for each one. A regular for-loop would not suffice because adding a button is not asynchronous. We will create an asynchronous loop by using recursion
function add_option_button(index) {
if (index === scenario.options.length) {
// Base case
return;
}
var option = scenario.options[index];
// Create a <button> for this option and append it to the #options <div>
$('<button>')
.html(option.name)
.click(function(e) {
// This is an onclick handler function. It decides what to do after the user has clicked on the button.
// First, prevent any default thing that the button is going to do, since we're specifying our own action for the button
e.preventDefault();
// We'll want to call display_scenario() with this option
display_scenario(option);
})
.appendTo('#options');
// Add the next option button
add_option_button(index + 1);
}
add_option_button(0);
}
// This function waits until the document is ready
$(document).ready(function() {
// Start the story
display_scenario({
name: null,
path: 'intro'
});
});
#import url(http://fonts.googleapis.com/css?family=Open+Sans:400,700);
* {
margin: 0px;
padding: 0px;
color: #32363F;
font: 18px 'Open Sans', sans-serif;
border: none;
outline: none;
box-sizing: border-box;
}
html {
display: table;
width: 100%;
height: 100%;
}
body {
display: table-cell;
background: #32363F;
vertical-align: middle;
}
#wrapper {
margin: 40px;
background: #D6C2A3;
width: calc(100% - 80px);
}
h1 {
display: block;
padding: 20px 20px 12px;
font: 700 36px 'Open Sans', sans-serif;
background: #E84949;
color: #FAFAFA;
text-transform: uppercase;
}
#prompt {
padding: 20px;
}
#prompt p {
padding-bottom: 8px;
}
#prompt p b {
font-weight: 700;
}
#options {
display: flex;
padding: 0px 20px 28px;
text-align: center;
}
#options button {
margin: 0px 8px;
padding: 8px 20px;
background: #C2AE8F;
width: 100%;
cursor: pointer;
}
#options button:hover,
#options button:active {
background: #E84949;
color: #FAFAFA;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
<h1>Food Adventure</h1>
<div id="prompt"></div>
<div id="options"></div>
</div>

Categories

Resources