I've created list of list containing some data about countries (grouped by subregions, each country contains following data: name, capital, population and area). Now I would like to add ability to hide or show all the countries belonging to its subregion. For example after clicking on subregion North America all the countries belonging to NA should show up, or hide if they were shown up already. Right now all I can do is to show the whole list of subregions with all its countries and I am clueless how to add the ability of dropdown. I will be extremely grateful for help.
Below is source code of what i was able to do.
let div = document.createElement('div');
document.body.appendChild(div);
let ul = document.createElement('ul');
div.appendChild(ul);
async function f() {
//fetching and sorting data by regions and subregions
const res = await fetch("https://restcountries.com/v3.1/all");
const data = await res.json();
data.sort((a, b) => {
if (a.region > b.region) return 1;
else if (a.region < b.region) return -1
else {
if (a.subregion > b.subregion) return 1;
else return -1;
}
})
//count no of subregions and totals of subregion area and population data
var prevSR = null;
var cntSR = 0;
var subregPop = [];
var subregArea = [];
var localPop = 0;
var localArea = 0;
for (const x of data) {
if (prevSR != x.subregion) {
cntSR += 1;
prevSR = x.subregion;
subregPop.push(localPop);
subregArea.push(localArea);
localArea = 0;
localPop = 0;
}
localArea += x.area;
localPop += x.population;
}
//loop to upload data to lists
var i = 0
prevSubregion = data[0].subregion;
for (var a = 0; a < cntSR; a++) {
//creating subregion
let li = createSubregion(data[i].subregion, subregPop[a + 1], subregArea[a + 1]);
let subOl = document.createElement('ol');
while (prevSubregion == data[i].subregion) {
//creating country
prevSubregion = data[i].subregion;
subLi = createCountry(data[i].name.common, data[i].capital, data[i].area, data[i].population);
subOl.appendChild(subLi);
i += 1;
}
prevSubregion = data[i].subregion;
li.appendChild(subOl);
ul.appendChild(li);
}
}
function createSubregion(name, population, area) {
var li = document.createElement("li");
li.setAttribute("class", "subregion");
var header = document.createElement("div");
header.setAttribute("class", "subregion-header disp-flex");
var nameDiv = document.createElement("div");
var nameh2 = document.createElement("h2");
nameh2.innerText = name;
nameDiv.appendChild(nameh2);
header.append(nameDiv);
var emptyDiv = document.createElement("div");
header.appendChild(emptyDiv);
var populationDiv = document.createElement("div");
var populationh2 = document.createElement("h3");
populationh2.innerText = population;
populationDiv.appendChild(populationh2);
header.append(populationDiv);
var areaDiv = document.createElement("div");
var areah2 = document.createElement("h3");
areah2.innerText = area;
areaDiv.appendChild(areah2);
header.append(areaDiv);
li.appendChild(header);
return li;
}
function createCountry(name, capital, area, population) {
var country = document.createElement("li");
country.setAttribute("class", "country disp-flex")
var namediv = document.createElement("div");
var nameh4 = document.createElement("h4");
nameh4.innerText = name;
namediv.appendChild(nameh4);
country.appendChild(namediv);
var capitaldiv = document.createElement("div");
var capitalh4 = document.createElement("h4");
capitalh4.innerText = capital;
capitaldiv.appendChild(capitalh4);
country.appendChild(capitaldiv);
var popdiv = document.createElement("div");
var poph4 = document.createElement("h4");
poph4.innerText = population;
popdiv.appendChild(poph4);
country.appendChild(popdiv);
var areadiv = document.createElement("div");
var areah4 = document.createElement("h4");
areah4.innerText = area;
areadiv.appendChild(areah4);
country.appendChild(areadiv);
return country;
}
f();
body {
min-height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: aliceblue;
font-family: 'Open Sans', Arial;
font-size: 18px;
}
header{
display:flex;
justify-content: space-between;
padding: 22px 0;
color:rgb(5, 5, 5);
}
ul {
list-style: none;
list-style-type: none;
outline: 2px solid #ddd;
padding: 1rem 2rem;
border-radius: 0.5rem;
list-style-position: inside;
color: blue;
}
ul ol {
color: rgb(197, 105, 18);
list-style: none;
list-style-type: none;
font-size: .9em;
margin: 0.4rem 0;
}
.country{
display: flex;
justify-content: space-between;
}
.disp-flex{
display:flex;
justify-content: space-between;
}
.disp-flex > div{
width:23%;
padding:15px 0px;
}
.subregion-header>div:nth-child(1){
position: relative;
left:30px;
}
<!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>
<link rel="stylesheet" href="style.css">
</head>
<body>
<main class="container">
<header>
<div id="name">
<h1>Name-</h1>
</div>
<div id="capital">
<h1>Capital-</h1>
</div>
<div id="population">
<h1>Population-</h1>
</div>
<div id="area">
<h1>Area</h1>
</div>
</header>
<script src="script.js"></script>
</main>
</body>
</html>
Second thing, but not as important as first, I would also need to add feature of sorting and filtering each column after clicking div element on the very top. So for example after clicking AREA, on the header section, countries should be sorted by their area. And the filter option allowing to show only countries that, for example, start with letter 'A'.
You can group the subregions first like,
const subRegions = data.reduce((r, a) => {
r[a.subregion] = r[a.subregion] || [];
r[a.subregion].push(a);
return r;
}, {});
And then create a select element and inject the text and value respectively.
Then handle the onchange and get the slected subregion data instead of all at once like subRegions[subRegionName] .
Forked example:
let div = document.createElement('div');
document.body.appendChild(div);
let ul = document.createElement('ul');
div.appendChild(ul);
async function f() {
//fetching and sorting data by regions and subregions
const res = await fetch("https://restcountries.com/v3.1/all");
const data = await res.json();
data.sort((a, b) => {
if (a.region > b.region) return 1;
else if (a.region < b.region) return -1
else {
if (a.subregion > b.subregion) return 1;
else return -1;
}
});
const container = document.getElementById('container');
const select = document.createElement('select');
const olWrapper = document.getElementById('listWrapper');
const subRegionWrapper = document.getElementById('subRegionWrapper');
const subRegions = data.reduce((r, a) => {
r[a.subregion] = r[a.subregion] || [];
r[a.subregion].push(a);
return r;
}, {});
const dropdownValues = Object.keys(subRegions);
const firstOption = document.createElement('option');
firstOption.value = -1;
firstOption.text = "Select a Subregion";
select.appendChild(firstOption);
dropdownValues.forEach(item => {
const option = document.createElement('option');
option.value = item;
option.text = item;
select.appendChild(option);
});
container.appendChild(select);
select.onchange = (e) => {
olWrapper.innerHTML = '';
const subRegionName = e.target.value;
const filteredValues = subRegions[subRegionName];
const totalArea = filteredValues.reduce((acc, curr) => acc+curr.area,0);
const totalPopulation = filteredValues.reduce((acc, curr) => acc+curr.population,0);
const li = createSubregion(subRegionName, totalPopulation, totalArea);
ul.innerHTML = '';
ul.appendChild(li);
subRegionWrapper.appendChild(ul);
filteredValues.forEach(item => {
const subLi = createCountry(item.name.common, item.capital, item.area, item.population);
const subOl = document.createElement('ol');
subOl.appendChild(subLi);
olWrapper.appendChild(subOl);
})
};
}
function createSubregion(name, population, area) {
var li = document.createElement("li");
li.setAttribute("class", "subregion");
var header = document.createElement("div");
header.setAttribute("class", "subregion-header disp-flex");
var nameDiv = document.createElement("div");
var nameh2 = document.createElement("h2");
nameh2.innerText = name;
nameDiv.appendChild(nameh2);
header.append(nameDiv);
var emptyDiv = document.createElement("div");
header.appendChild(emptyDiv);
var populationDiv = document.createElement("div");
var populationh2 = document.createElement("h3");
populationh2.innerText = population;
populationDiv.appendChild(populationh2);
header.append(populationDiv);
var areaDiv = document.createElement("div");
var areah2 = document.createElement("h3");
areah2.innerText = area;
areaDiv.appendChild(areah2);
header.append(areaDiv);
li.appendChild(header);
return li;
}
function createCountry(name, capital, area, population) {
var country = document.createElement("li");
country.setAttribute("class", "country disp-flex")
var namediv = document.createElement("div");
var nameh4 = document.createElement("h4");
nameh4.innerText = name;
namediv.appendChild(nameh4);
country.appendChild(namediv);
var capitaldiv = document.createElement("div");
var capitalh4 = document.createElement("h4");
capitalh4.innerText = capital;
capitaldiv.appendChild(capitalh4);
country.appendChild(capitaldiv);
var popdiv = document.createElement("div");
var poph4 = document.createElement("h4");
poph4.innerText = population;
popdiv.appendChild(poph4);
country.appendChild(popdiv);
var areadiv = document.createElement("div");
var areah4 = document.createElement("h4");
areah4.innerText = area;
areadiv.appendChild(areah4);
country.appendChild(areadiv);
return country;
}
f();
body {
min-height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: aliceblue;
font-family: 'Open Sans', Arial;
font-size: 18px;
}
header{
display:flex;
justify-content: space-between;
padding: 22px 0;
color:rgb(5, 5, 5);
}
ul {
list-style: none;
list-style-type: none;
outline: 2px solid #ddd;
padding: 1rem 2rem;
border-radius: 0.5rem;
list-style-position: inside;
color: blue;
}
ul ol {
color: rgb(197, 105, 18);
list-style: none;
list-style-type: none;
font-size: .9em;
margin: 0.4rem 0;
}
.country{
display: flex;
justify-content: space-between;
}
.disp-flex{
display:flex;
justify-content: space-between;
}
.disp-flex > div{
width:23%;
padding:15px 0px;
}
.subregion-header>div:nth-child(1){
position: relative;
left:30px;
}
<!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>
<link rel="stylesheet" href="style.css">
</head>
<body>
<main class="container">
<header>
<div id="name">
<h1>Name-</h1>
</div>
<div id="capital">
<h1>Capital-</h1>
</div>
<div id="population">
<h1>Population-</h1>
</div>
<div id="area">
<h1>Area</h1>
</div>
</header>
<div id="container"></div>
<div id="subRegionWrapper"> </div>
<div id="listWrapper"></div>
</script>
</main>
</body>
</html>
Update:
Here is the updated version with each sub region is grouped as an accordion and on toggle, the respective countries under the sub region were displayed..
let div = document.createElement('div');
document.body.appendChild(div);
let ul = document.createElement('ul');
div.appendChild(ul);
async function f() {
//fetching and sorting data by regions and subregions
const res = await fetch("https://restcountries.com/v3.1/all");
const data = await res.json();
data.sort((a, b) => {
if (a.region > b.region) return 1;
else if (a.region < b.region) return -1
else {
if (a.subregion > b.subregion) return 1;
else return -1;
}
});
const container = document.getElementById('container');
const accordion = document.createElement('div');
const olWrapper = document.getElementById('listWrapper');
const subRegionWrapper = document.getElementById('subRegionWrapper');
const subRegions = data.reduce((r, a) => {
r[a.subregion] = r[a.subregion] || [];
r[a.subregion].push(a);
return r;
}, {});
const dropdownValues = Object.entries(subRegions);
dropdownValues.forEach(subRegion => {
const accordionWrapper = document.createElement('div');
const panel = document.createElement('div');
panel.classList.add('panel');
accordionWrapper.classList.add('accordion');
const totalArea = subRegion[1].reduce((acc, curr) => acc+curr.area,0);
const totalPopulation = subRegion[1].reduce((acc, curr) => acc+curr.population,0);
const li = createSubregion(subRegion[0], totalPopulation, totalArea);
accordionWrapper.appendChild(li);
accordion.appendChild(accordionWrapper);
subRegion[1].forEach(item => {
const subLi = createCountry(item.name.common, item.capital, item.area, item.population);
const subOl = document.createElement('ol');
subOl.appendChild(subLi);
panel.appendChild(subOl);
accordion.appendChild(panel);
});
accordionWrapper.addEventListener('click', function() {
this.classList.toggle("active");
const panel = this.nextElementSibling;
if (panel.style.display === "block") {
panel.style.display = "none";
} else {
panel.style.display = "block";
}
});
});
container.appendChild(accordion);
}
function createSubregion(name, population, area) {
var li = document.createElement("li");
li.setAttribute("class", "subregion");
var header = document.createElement("div");
header.setAttribute("class", "subregion-header disp-flex");
var nameDiv = document.createElement("div");
var nameh2 = document.createElement("h2");
nameh2.innerText = name;
nameDiv.appendChild(nameh2);
header.append(nameDiv);
var emptyDiv = document.createElement("div");
header.appendChild(emptyDiv);
var populationDiv = document.createElement("div");
var populationh2 = document.createElement("h3");
populationh2.innerText = population;
populationDiv.appendChild(populationh2);
header.append(populationDiv);
var areaDiv = document.createElement("div");
var areah2 = document.createElement("h3");
areah2.innerText = area;
areaDiv.appendChild(areah2);
header.append(areaDiv);
li.appendChild(header);
return li;
}
function createCountry(name, capital, area, population) {
var country = document.createElement("li");
country.setAttribute("class", "country disp-flex")
var namediv = document.createElement("div");
var nameh4 = document.createElement("h4");
nameh4.innerText = name;
namediv.appendChild(nameh4);
country.appendChild(namediv);
var capitaldiv = document.createElement("div");
var capitalh4 = document.createElement("h4");
capitalh4.innerText = capital;
capitaldiv.appendChild(capitalh4);
country.appendChild(capitaldiv);
var popdiv = document.createElement("div");
var poph4 = document.createElement("h4");
poph4.innerText = population;
popdiv.appendChild(poph4);
country.appendChild(popdiv);
var areadiv = document.createElement("div");
var areah4 = document.createElement("h4");
areah4.innerText = area;
areadiv.appendChild(areah4);
country.appendChild(areadiv);
return country;
}
f();
body {
min-height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: aliceblue;
font-family: 'Open Sans', Arial;
font-size: 18px;
}
header{
display:flex;
justify-content: space-between;
padding: 22px 0;
color:rgb(5, 5, 5);
}
ul {
list-style: none;
list-style-type: none;
outline: 2px solid #ddd;
padding: 1rem 2rem;
border-radius: 0.5rem;
list-style-position: inside;
color: blue;
}
ul ol {
color: rgb(197, 105, 18);
list-style: none;
list-style-type: none;
font-size: .9em;
margin: 0.4rem 0;
}
.country{
display: flex;
justify-content: space-between;
}
.disp-flex{
display:flex;
justify-content: space-between;
}
.disp-flex > div{
width:23%;
padding:15px 0px;
}
.subregion-header>div:nth-child(1){
position: relative;
left:30px;
}
.accordion {
background-color: #eee;
color: #444;
cursor: pointer;
padding: 18px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 15px;
transition: 0.4s;
margin: 15px 2px;
}
.accordion li {
list-style-type: none;
}
.active, .accordion:hover {
background-color: #ccc;
}
.panel {
padding: 0 18px;
display: none;
background-color: white;
overflow: hidden;
}
<!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>
<link rel="stylesheet" href="style.css">
</head>
<body>
<main class="container">
<header>
<div id="name">
<h1>Name-</h1>
</div>
<div id="capital">
<h1>Capital-</h1>
</div>
<div id="population">
<h1>Population-</h1>
</div>
<div id="area">
<h1>Area</h1>
</div>
</header>
<div id="container"></div>
<div id="subRegionWrapper"> </div>
<div id="listWrapper"></div>
</script>
</main>
</body>
</html>
Related
I currently have this on my screen:
I am struggling to achieve the following: 1) delete the black shape outline in the background (you can see it between cards), and 2) create a white gap between each pair of adjacent cards.
Does anyone have any ideas on how to achieve this? Thank you very much!
I am pasting the code below:
HTML:
const SUITS = ["♥", "♦", "♠", "♣"];
const VALUES = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];
class Deck{
constructor(cards = freshDeck()){
this.cards = cards
}
}
class Card{
constructor(suit, value){
this.suit = suit;
this.value = value;
}
get color(){
return this.suit === '♣'|| this.suit === '♠' ? 'black' : 'red'
}
// Create HTML for the card
getHTML(){
const cardDiv = document.createElement('div');
cardDiv.innerText = this.suit;
cardDiv.classList.add("card", this.color);
cardDiv.dataset.value = `${this.value} ${this.suit}`;
return cardDiv;
}
}
function freshDeck(){
return SUITS.flatMap(suit => {
return VALUES.map(value => {
return new Card(suit, value)
})
})
}
const deck = new Deck();
const clubsCardSlot = document.querySelector('.clubs');
const diamondsCardSlot = document.querySelector('.diamonds');
const heartsCardSlot = document.querySelector('.hearts');
const spadesCardSlot = document.querySelector('.spades');
const heartsCards = new Deck(deck.cards.slice(0,13));
const diamondsCards = new Deck(deck.cards.slice(13,26));
const spadesCards = new Deck(deck.cards.slice(26,39));
const clubsCards = new Deck(deck.cards.slice(39,52));
const heartA = heartsCards.cards[0];
const heart2 = heartsCards.cards[1];
const heart3 = heartsCards.cards[2];
const heart4 = heartsCards.cards[3];
const heart5 = heartsCards.cards[4];
const heart6 = heartsCards.cards[5];
const heart7 = heartsCards.cards[6];
const heart8 = heartsCards.cards[7];
const heart9 = heartsCards.cards[8];
const heart10 = heartsCards.cards[9];
const heartJ = heartsCards.cards[10];
const heartQ = heartsCards.cards[11];
const heartK = heartsCards.cards[12];
const diamondA = diamondsCards.cards[0];
const diamond2 = diamondsCards.cards[1];
const diamond3 = diamondsCards.cards[2];
const diamond4 = diamondsCards.cards[3];
const diamond5 = diamondsCards.cards[4];
const diamond6 = diamondsCards.cards[5];
const diamond7 = diamondsCards.cards[6];
const diamond8 = diamondsCards.cards[7];
const diamond9 = diamondsCards.cards[8];
const diamond10 = diamondsCards.cards[9];
const diamondJ = diamondsCards.cards[10];
const diamondQ = diamondsCards.cards[11];
const diamondK = diamondsCards.cards[12];
const spadeA = spadesCards.cards[0];
const spade2 = spadesCards.cards[1];
const spade3 = spadesCards.cards[2];
const spade4 = spadesCards.cards[3];
const spade5 = spadesCards.cards[4];
const spade6 = spadesCards.cards[5];
const spade7 = spadesCards.cards[6];
const spade8 = spadesCards.cards[7];
const spade9 = spadesCards.cards[8];
const spade10 = spadesCards.cards[9];
const spadeJ = spadesCards.cards[10];
const spadeQ = spadesCards.cards[11];
const spadeK = spadesCards.cards[12];
const clubA = clubsCards.cards[0];
const club2 = clubsCards.cards[1];
const club3 = clubsCards.cards[2];
const club4 = clubsCards.cards[3];
const club5 = clubsCards.cards[4];
const club6 = clubsCards.cards[5];
const club7 = clubsCards.cards[6];
const club8 = clubsCards.cards[7];
const club9 = clubsCards.cards[8];
const club10 = clubsCards.cards[9];
const clubJ = clubsCards.cards[10];
const clubQ = clubsCards.cards[11];
const clubK = clubsCards.cards[12];
heartsCardSlot.appendChild(heartA.getHTML());
heartsCardSlot.appendChild(heart2.getHTML());
heartsCardSlot.appendChild(heart3.getHTML());
heartsCardSlot.appendChild(heart4.getHTML());
heartsCardSlot.appendChild(heart5.getHTML());
heartsCardSlot.appendChild(heart6.getHTML());
heartsCardSlot.appendChild(heart7.getHTML());
heartsCardSlot.appendChild(heart8.getHTML());
heartsCardSlot.appendChild(heart9.getHTML());
heartsCardSlot.appendChild(heart10.getHTML());
heartsCardSlot.appendChild(heartJ.getHTML());
heartsCardSlot.appendChild(heartQ.getHTML());
heartsCardSlot.appendChild(heartK.getHTML());
diamondsCardSlot.appendChild(diamondA.getHTML());
diamondsCardSlot.appendChild(diamond2.getHTML());
diamondsCardSlot.appendChild(diamond3.getHTML());
diamondsCardSlot.appendChild(diamond4.getHTML());
diamondsCardSlot.appendChild(diamond5.getHTML());
diamondsCardSlot.appendChild(diamond6.getHTML());
diamondsCardSlot.appendChild(diamond7.getHTML());
diamondsCardSlot.appendChild(diamond8.getHTML());
diamondsCardSlot.appendChild(diamond9.getHTML());
diamondsCardSlot.appendChild(diamond10.getHTML());
diamondsCardSlot.appendChild(diamondJ.getHTML());
diamondsCardSlot.appendChild(diamondQ.getHTML());
diamondsCardSlot.appendChild(diamondK.getHTML());
spadesCardSlot.appendChild(spadeA.getHTML());
spadesCardSlot.appendChild(spade2.getHTML());
spadesCardSlot.appendChild(spade3.getHTML());
spadesCardSlot.appendChild(spade4.getHTML());
spadesCardSlot.appendChild(spade5.getHTML());
spadesCardSlot.appendChild(spade6.getHTML());
spadesCardSlot.appendChild(spade7.getHTML());
spadesCardSlot.appendChild(spade8.getHTML());
spadesCardSlot.appendChild(spade9.getHTML());
spadesCardSlot.appendChild(spade10.getHTML());
spadesCardSlot.appendChild(spadeJ.getHTML());
spadesCardSlot.appendChild(spadeQ.getHTML());
spadesCardSlot.appendChild(spadeK.getHTML());
clubsCardSlot.appendChild(clubA.getHTML());
clubsCardSlot.appendChild(club2.getHTML());
clubsCardSlot.appendChild(club3.getHTML());
clubsCardSlot.appendChild(club4.getHTML());
clubsCardSlot.appendChild(club5.getHTML());
clubsCardSlot.appendChild(club6.getHTML());
clubsCardSlot.appendChild(club7.getHTML());
clubsCardSlot.appendChild(club8.getHTML());
clubsCardSlot.appendChild(club9.getHTML());
clubsCardSlot.appendChild(club10.getHTML());
clubsCardSlot.appendChild(clubJ.getHTML());
clubsCardSlot.appendChild(clubQ.getHTML());
clubsCardSlot.appendChild(clubK.getHTML());
*, *::after, *::before {
box-sizing: border-box;
}
body {
margin: 2;
display:grid;
grid-template-columns: 1000px;
grid-template-rows: 7rem 2 rem 7rem 2 rem 7 rem 2 rem 7rem;
column-gap: 3rem;
row-gap: 1.5rem;
cursor: pointer;
justify-content: center;
padding-top: 5rem;
}
div {
outline: none;
font-size: 100px;
width:50%;
}
.card-slot{
height: 100%;
width: 100%;
border: 1px solid black;
display: flex;
justify-content: center;
align-items: center;
font-size: 3rem;
border-radius: 0.5rem;
color: white;
user-select: none;
}
.gap{
grid-column: span 13;
display: flex;
justify-content: center;
align-items: center;
}
.card{
position: relative;
height: 100%;
width: 100%;
border: 1px solid black;
border-radius: .5rem;
display: flex;
justify-content: center;
align-items: center;
font-size: 6rem;
}
.card.red{
color: red;
}
.card.black{
color: black;
}
.card::before,
.card::after{
position: absolute;
content: attr(data-value);
font-size: 0.9rem;
}
.card::before{
top: .5rem;
left: .5rem;
}
.card::after{
bottom: .5rem;
right: .5rem;
transform: rotate(180deg);
}
<!DOCTYPE html>
<html lang="eng-UK">
<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">
<title>Card Game</title>
<script src = "scripts/card-game/card_game_screenshot.js" type = "module"></script>
<link rel="stylesheet" href= "styles/card-game/styles_screenshot.css">
</head>
<body>
<div class="clubs card-slot"></div>
<div class="gap"></div>
<div class="diamonds card-slot"></div>
<div class="gap"></div>
<div class="hearts card-slot"></div>
<div class="gap"></div>
<div class="spades card-slot"></div>
</body>
</html>
There is 2 things to edit :
Remove the border for the card-slot
Add margin-right to the class card
const SUITS = ["♥", "♦", "♠", "♣"];
const VALUES = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];
class Deck{
constructor(cards = freshDeck()){
this.cards = cards
}
}
class Card{
constructor(suit, value){
this.suit = suit;
this.value = value;
}
get color(){
return this.suit === '♣'|| this.suit === '♠' ? 'black' : 'red'
}
// Create HTML for the card
getHTML(){
const cardDiv = document.createElement('div');
cardDiv.innerText = this.suit;
cardDiv.classList.add("card", this.color);
cardDiv.dataset.value = `${this.value} ${this.suit}`;
return cardDiv;
}
}
function freshDeck(){
return SUITS.flatMap(suit => {
return VALUES.map(value => {
return new Card(suit, value)
})
})
}
const deck = new Deck();
const clubsCardSlot = document.querySelector('.clubs');
const diamondsCardSlot = document.querySelector('.diamonds');
const heartsCardSlot = document.querySelector('.hearts');
const spadesCardSlot = document.querySelector('.spades');
const heartsCards = new Deck(deck.cards.slice(0,13));
const diamondsCards = new Deck(deck.cards.slice(13,26));
const spadesCards = new Deck(deck.cards.slice(26,39));
const clubsCards = new Deck(deck.cards.slice(39,52));
const heartA = heartsCards.cards[0];
const heart2 = heartsCards.cards[1];
const heart3 = heartsCards.cards[2];
const heart4 = heartsCards.cards[3];
const heart5 = heartsCards.cards[4];
const heart6 = heartsCards.cards[5];
const heart7 = heartsCards.cards[6];
const heart8 = heartsCards.cards[7];
const heart9 = heartsCards.cards[8];
const heart10 = heartsCards.cards[9];
const heartJ = heartsCards.cards[10];
const heartQ = heartsCards.cards[11];
const heartK = heartsCards.cards[12];
const diamondA = diamondsCards.cards[0];
const diamond2 = diamondsCards.cards[1];
const diamond3 = diamondsCards.cards[2];
const diamond4 = diamondsCards.cards[3];
const diamond5 = diamondsCards.cards[4];
const diamond6 = diamondsCards.cards[5];
const diamond7 = diamondsCards.cards[6];
const diamond8 = diamondsCards.cards[7];
const diamond9 = diamondsCards.cards[8];
const diamond10 = diamondsCards.cards[9];
const diamondJ = diamondsCards.cards[10];
const diamondQ = diamondsCards.cards[11];
const diamondK = diamondsCards.cards[12];
const spadeA = spadesCards.cards[0];
const spade2 = spadesCards.cards[1];
const spade3 = spadesCards.cards[2];
const spade4 = spadesCards.cards[3];
const spade5 = spadesCards.cards[4];
const spade6 = spadesCards.cards[5];
const spade7 = spadesCards.cards[6];
const spade8 = spadesCards.cards[7];
const spade9 = spadesCards.cards[8];
const spade10 = spadesCards.cards[9];
const spadeJ = spadesCards.cards[10];
const spadeQ = spadesCards.cards[11];
const spadeK = spadesCards.cards[12];
const clubA = clubsCards.cards[0];
const club2 = clubsCards.cards[1];
const club3 = clubsCards.cards[2];
const club4 = clubsCards.cards[3];
const club5 = clubsCards.cards[4];
const club6 = clubsCards.cards[5];
const club7 = clubsCards.cards[6];
const club8 = clubsCards.cards[7];
const club9 = clubsCards.cards[8];
const club10 = clubsCards.cards[9];
const clubJ = clubsCards.cards[10];
const clubQ = clubsCards.cards[11];
const clubK = clubsCards.cards[12];
heartsCardSlot.appendChild(heartA.getHTML());
heartsCardSlot.appendChild(heart2.getHTML());
heartsCardSlot.appendChild(heart3.getHTML());
heartsCardSlot.appendChild(heart4.getHTML());
heartsCardSlot.appendChild(heart5.getHTML());
heartsCardSlot.appendChild(heart6.getHTML());
heartsCardSlot.appendChild(heart7.getHTML());
heartsCardSlot.appendChild(heart8.getHTML());
heartsCardSlot.appendChild(heart9.getHTML());
heartsCardSlot.appendChild(heart10.getHTML());
heartsCardSlot.appendChild(heartJ.getHTML());
heartsCardSlot.appendChild(heartQ.getHTML());
heartsCardSlot.appendChild(heartK.getHTML());
diamondsCardSlot.appendChild(diamondA.getHTML());
diamondsCardSlot.appendChild(diamond2.getHTML());
diamondsCardSlot.appendChild(diamond3.getHTML());
diamondsCardSlot.appendChild(diamond4.getHTML());
diamondsCardSlot.appendChild(diamond5.getHTML());
diamondsCardSlot.appendChild(diamond6.getHTML());
diamondsCardSlot.appendChild(diamond7.getHTML());
diamondsCardSlot.appendChild(diamond8.getHTML());
diamondsCardSlot.appendChild(diamond9.getHTML());
diamondsCardSlot.appendChild(diamond10.getHTML());
diamondsCardSlot.appendChild(diamondJ.getHTML());
diamondsCardSlot.appendChild(diamondQ.getHTML());
diamondsCardSlot.appendChild(diamondK.getHTML());
spadesCardSlot.appendChild(spadeA.getHTML());
spadesCardSlot.appendChild(spade2.getHTML());
spadesCardSlot.appendChild(spade3.getHTML());
spadesCardSlot.appendChild(spade4.getHTML());
spadesCardSlot.appendChild(spade5.getHTML());
spadesCardSlot.appendChild(spade6.getHTML());
spadesCardSlot.appendChild(spade7.getHTML());
spadesCardSlot.appendChild(spade8.getHTML());
spadesCardSlot.appendChild(spade9.getHTML());
spadesCardSlot.appendChild(spade10.getHTML());
spadesCardSlot.appendChild(spadeJ.getHTML());
spadesCardSlot.appendChild(spadeQ.getHTML());
spadesCardSlot.appendChild(spadeK.getHTML());
clubsCardSlot.appendChild(clubA.getHTML());
clubsCardSlot.appendChild(club2.getHTML());
clubsCardSlot.appendChild(club3.getHTML());
clubsCardSlot.appendChild(club4.getHTML());
clubsCardSlot.appendChild(club5.getHTML());
clubsCardSlot.appendChild(club6.getHTML());
clubsCardSlot.appendChild(club7.getHTML());
clubsCardSlot.appendChild(club8.getHTML());
clubsCardSlot.appendChild(club9.getHTML());
clubsCardSlot.appendChild(club10.getHTML());
clubsCardSlot.appendChild(clubJ.getHTML());
clubsCardSlot.appendChild(clubQ.getHTML());
clubsCardSlot.appendChild(clubK.getHTML());
*, *::after, *::before {
box-sizing: border-box;
}
body {
margin: 2;
display:grid;
grid-template-columns: 1000px;
grid-template-rows: 7rem 2 rem 7rem 2 rem 7 rem 2 rem 7rem;
column-gap: 3rem;
row-gap: 1.5rem;
cursor: pointer;
justify-content: center;
padding-top: 5rem;
}
div {
outline: none;
font-size: 100px;
width:50%;
}
.card-slot{
height: 100%;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
font-size: 3rem;
border-radius: 0.5rem;
color: white;
user-select: none;
}
.gap{
grid-column: span 13;
display: flex;
justify-content: center;
align-items: center;
}
.card{
position: relative;
height: 100%;
width: 100%;
border: 1px solid black;
border-radius: .5rem;
display: flex;
justify-content: center;
align-items: center;
font-size: 6rem;
margin-right: 5px;
}
.card.red{
color: red;
}
.card.black{
color: black;
}
.card::before,
.card::after{
position: absolute;
content: attr(data-value);
font-size: 0.9rem;
}
.card::before{
top: .5rem;
left: .5rem;
}
.card::after{
bottom: .5rem;
right: .5rem;
transform: rotate(180deg);
}
<!DOCTYPE html>
<html lang="eng-UK">
<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">
<title>Card Game</title>
<script src = "scripts/card-game/card_game_screenshot.js" type = "module"></script>
<link rel="stylesheet" href= "styles/card-game/styles_screenshot.css">
</head>
<body>
<div class="clubs card-slot"></div>
<div class="gap"></div>
<div class="diamonds card-slot"></div>
<div class="gap"></div>
<div class="hearts card-slot"></div>
<div class="gap"></div>
<div class="spades card-slot"></div>
</body>
</html>
const SUITS = ["♥", "♦", "♠", "♣"];
const VALUES = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];
class Deck{
constructor(cards = freshDeck()){
this.cards = cards
}
}
class Card{
constructor(suit, value){
this.suit = suit;
this.value = value;
}
get color(){
return this.suit === '♣'|| this.suit === '♠' ? 'black' : 'red'
}
// Create HTML for the card
getHTML(){
const cardDiv = document.createElement('div');
cardDiv.innerText = this.suit;
cardDiv.classList.add("card", this.color);
cardDiv.dataset.value = `${this.value} ${this.suit}`;
return cardDiv;
}
}
function freshDeck(){
return SUITS.flatMap(suit => {
return VALUES.map(value => {
return new Card(suit, value)
})
})
}
const deck = new Deck();
const clubsCardSlot = document.querySelector('.clubs');
const diamondsCardSlot = document.querySelector('.diamonds');
const heartsCardSlot = document.querySelector('.hearts');
const spadesCardSlot = document.querySelector('.spades');
const heartsCards = new Deck(deck.cards.slice(0,13));
const diamondsCards = new Deck(deck.cards.slice(13,26));
const spadesCards = new Deck(deck.cards.slice(26,39));
const clubsCards = new Deck(deck.cards.slice(39,52));
const heartA = heartsCards.cards[0];
const heart2 = heartsCards.cards[1];
const heart3 = heartsCards.cards[2];
const heart4 = heartsCards.cards[3];
const heart5 = heartsCards.cards[4];
const heart6 = heartsCards.cards[5];
const heart7 = heartsCards.cards[6];
const heart8 = heartsCards.cards[7];
const heart9 = heartsCards.cards[8];
const heart10 = heartsCards.cards[9];
const heartJ = heartsCards.cards[10];
const heartQ = heartsCards.cards[11];
const heartK = heartsCards.cards[12];
const diamondA = diamondsCards.cards[0];
const diamond2 = diamondsCards.cards[1];
const diamond3 = diamondsCards.cards[2];
const diamond4 = diamondsCards.cards[3];
const diamond5 = diamondsCards.cards[4];
const diamond6 = diamondsCards.cards[5];
const diamond7 = diamondsCards.cards[6];
const diamond8 = diamondsCards.cards[7];
const diamond9 = diamondsCards.cards[8];
const diamond10 = diamondsCards.cards[9];
const diamondJ = diamondsCards.cards[10];
const diamondQ = diamondsCards.cards[11];
const diamondK = diamondsCards.cards[12];
const spadeA = spadesCards.cards[0];
const spade2 = spadesCards.cards[1];
const spade3 = spadesCards.cards[2];
const spade4 = spadesCards.cards[3];
const spade5 = spadesCards.cards[4];
const spade6 = spadesCards.cards[5];
const spade7 = spadesCards.cards[6];
const spade8 = spadesCards.cards[7];
const spade9 = spadesCards.cards[8];
const spade10 = spadesCards.cards[9];
const spadeJ = spadesCards.cards[10];
const spadeQ = spadesCards.cards[11];
const spadeK = spadesCards.cards[12];
const clubA = clubsCards.cards[0];
const club2 = clubsCards.cards[1];
const club3 = clubsCards.cards[2];
const club4 = clubsCards.cards[3];
const club5 = clubsCards.cards[4];
const club6 = clubsCards.cards[5];
const club7 = clubsCards.cards[6];
const club8 = clubsCards.cards[7];
const club9 = clubsCards.cards[8];
const club10 = clubsCards.cards[9];
const clubJ = clubsCards.cards[10];
const clubQ = clubsCards.cards[11];
const clubK = clubsCards.cards[12];
heartsCardSlot.appendChild(heartA.getHTML());
heartsCardSlot.appendChild(heart2.getHTML());
heartsCardSlot.appendChild(heart3.getHTML());
heartsCardSlot.appendChild(heart4.getHTML());
heartsCardSlot.appendChild(heart5.getHTML());
heartsCardSlot.appendChild(heart6.getHTML());
heartsCardSlot.appendChild(heart7.getHTML());
heartsCardSlot.appendChild(heart8.getHTML());
heartsCardSlot.appendChild(heart9.getHTML());
heartsCardSlot.appendChild(heart10.getHTML());
heartsCardSlot.appendChild(heartJ.getHTML());
heartsCardSlot.appendChild(heartQ.getHTML());
heartsCardSlot.appendChild(heartK.getHTML());
diamondsCardSlot.appendChild(diamondA.getHTML());
diamondsCardSlot.appendChild(diamond2.getHTML());
diamondsCardSlot.appendChild(diamond3.getHTML());
diamondsCardSlot.appendChild(diamond4.getHTML());
diamondsCardSlot.appendChild(diamond5.getHTML());
diamondsCardSlot.appendChild(diamond6.getHTML());
diamondsCardSlot.appendChild(diamond7.getHTML());
diamondsCardSlot.appendChild(diamond8.getHTML());
diamondsCardSlot.appendChild(diamond9.getHTML());
diamondsCardSlot.appendChild(diamond10.getHTML());
diamondsCardSlot.appendChild(diamondJ.getHTML());
diamondsCardSlot.appendChild(diamondQ.getHTML());
diamondsCardSlot.appendChild(diamondK.getHTML());
spadesCardSlot.appendChild(spadeA.getHTML());
spadesCardSlot.appendChild(spade2.getHTML());
spadesCardSlot.appendChild(spade3.getHTML());
spadesCardSlot.appendChild(spade4.getHTML());
spadesCardSlot.appendChild(spade5.getHTML());
spadesCardSlot.appendChild(spade6.getHTML());
spadesCardSlot.appendChild(spade7.getHTML());
spadesCardSlot.appendChild(spade8.getHTML());
spadesCardSlot.appendChild(spade9.getHTML());
spadesCardSlot.appendChild(spade10.getHTML());
spadesCardSlot.appendChild(spadeJ.getHTML());
spadesCardSlot.appendChild(spadeQ.getHTML());
spadesCardSlot.appendChild(spadeK.getHTML());
clubsCardSlot.appendChild(clubA.getHTML());
clubsCardSlot.appendChild(club2.getHTML());
clubsCardSlot.appendChild(club3.getHTML());
clubsCardSlot.appendChild(club4.getHTML());
clubsCardSlot.appendChild(club5.getHTML());
clubsCardSlot.appendChild(club6.getHTML());
clubsCardSlot.appendChild(club7.getHTML());
clubsCardSlot.appendChild(club8.getHTML());
clubsCardSlot.appendChild(club9.getHTML());
clubsCardSlot.appendChild(club10.getHTML());
clubsCardSlot.appendChild(clubJ.getHTML());
clubsCardSlot.appendChild(clubQ.getHTML());
clubsCardSlot.appendChild(clubK.getHTML());
*, *::after, *::before {
box-sizing: border-box;
}
body {
margin: 2;
display:grid;
grid-template-columns: 1000px;
grid-template-rows: 7rem 2 rem 7rem 2 rem 7 rem 2 rem 7rem;
column-gap: 3rem;
row-gap: 1.5rem;
cursor: pointer;
justify-content: center;
padding-top: 5rem;
}
div {
outline: none;
font-size: 100px;
width:50%;
}
.card-slot{
height: 100%;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
font-size: 3rem;
border-radius: 0.5rem;
color: white;
user-select: none;
}
.gap{
grid-column: span 13;
display: flex;
justify-content: center;
align-items: center;
}
.card{
margin-left: 0.05em;
position: relative;
height: 100%;
width: 100%;
border: 1px solid black;
border-radius: .5rem;
display: flex;
justify-content: center;
align-items: center;
font-size: 6rem;
}
.card.red{
color: red;
}
.card.black{
color: black;
}
.card::before,
.card::after{
position: absolute;
content: attr(data-value);
font-size: 0.9rem;
}
.card::before{
top: .5rem;
left: .5rem;
}
.card::after{
bottom: .5rem;
right: .5rem;
transform: rotate(180deg);
}
<!DOCTYPE html>
<html lang="eng-UK">
<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">
<title>Card Game</title>
<script src = "scripts/card-game/card_game_screenshot.js" type = "module"></script>
<link rel="stylesheet" href= "styles/card-game/styles_screenshot.css">
</head>
<body>
<div class="clubs card-slot"></div>
<div class="gap"></div>
<div class="diamonds card-slot"></div>
<div class="gap"></div>
<div class="hearts card-slot"></div>
<div class="gap"></div>
<div class="spades card-slot"></div>
</body>
</html>
Just wanted to know easiest way to achieve this
Perhaps something like this:
(()=>
{
const formEls = document.querySelectorAll(".input-tags");
for(let i = 0; i < formEls.length; i++)
{
const formEl = formEls[i],
inputEl = document.createElement("input"),
tagsEl = document.createElement("span"),
listEl = document.createElement("datalist");
formEl.tags = [];
Object.defineProperties(formEl, {
list: {
get(){return getData(this, "list")},
set(val){this.dataset.list = val}
},
tags: {
get(){return getData(this, "tags")},
set(val){this.dataset.tags = val}
},
value:
{
get(){return this.dataset.value || ""},
set(val){this.dataset.value = val}
}
});
const list = formEl.list;
listEl.id = "input-tags-datalist" + i;
inputEl.setAttribute("list", listEl.id);
inputEl.type = "text";
tagsEl.className = "tags";
for(let i = 0, optionEl = document.createElement("option"); i < list.length; i++)
{
optionEl = optionEl.cloneNode(false);
optionEl.value = list[i];
listEl.appendChild(optionEl);
}
formEl.appendChild(tagsEl);
formEl.appendChild(inputEl);
formEl.appendChild(listEl);
inputEl._isClicked = true;
inputEl.addEventListener("keydown", e => inputEl._isClicked = !e.keyCode || e.keyCode==13);
inputEl.addEventListener("keyup", e => inputEl._isClicked = true);
inputEl.addEventListener("input", e =>
{
formEl.value = inputEl.value;
if (!inputEl._isClicked && !inputEl.value.match(/(^[^"']+ $)|(^(["']).+\3$)/))
{
dispatchEvent(formEl, "input");
return inputWidth(formEl);
}
const val = inputEl.value.replace(/^\s*((["'])([^"']+)\2|([^"']+)\s+)$/, "$4$3").replace(/[^\w -_]+/g, "").replace(/[ ]{2,}/g, " ");
if (formEl.dataset.autotags !== undefined || formEl.list.indexOf(val) != -1)
{
inputEl.value = val;
addTag(inputEl);
}
formEl.value = inputEl.value;
dispatchEvent(formEl, "input");
inputWidth(formEl);
});//inputEl.oninput()
tagsEl.addEventListener("click", e =>
{
if (!e.target.parentNode.classList.contains("tag"))
return;
const tag = e.target.parentNode.textContent,
list = formEl.list,
tags = formEl.tags,
index = list.indexOf(tag),
optionEl = listEl.children[index];
if (optionEl.classList.contains("new"))
{
list.splice(index, 1);
optionEl.parentNode.removeChild(optionEl);
}
else
optionEl.disabled = false;
tags.splice(tags.indexOf(tag), 1);
formEl.tags = tags;
formEl.list = list;
e.target.parentNode.parentNode.removeChild(e.target.parentNode);
inputWidth(formEl);
e.stopPropagation();
formEl.click();
dispatchEvent(formEl, "input");
});//tagsEl.onclick()
formEl.addEventListener("click", e => inputEl.focus());
inputWidth(formEl);
}
function dispatchEvent(el, type, opts)
{
return el.dispatchEvent(new Event(type, opts));
}
function inputWidth(formEl)
{
const inputEl = formEl.querySelector("input");
inputEl.style.width = "1em"; //min width
const inputStyle = window.getComputedStyle(inputEl),
formStyle = window.getComputedStyle(inputEl.parentNode),
inputRect = inputEl.getBoundingClientRect(),
formRect = inputEl.parentNode.getBoundingClientRect(),
canvas = document.createElement('canvas'),
ctx = canvas.getContext("2d");
ctx.font = inputStyle.font;
const widthText = (ctx.measureText(inputEl.value).width
+ parseFloat(inputStyle.paddingLeft)
+ parseFloat(inputStyle.paddingRight)
+ parseFloat(inputStyle.textIndent)
+ parseFloat(inputStyle.borderLeftWidth)
+ parseFloat(inputStyle.borderRightWidth)
+ 1
),
widthBox = formRect.right - inputRect.left - parseFloat(formStyle.paddingLeft) - parseFloat(formStyle.paddingRight) - 1;
inputEl.style.width = Math.max(widthText, widthBox) + "px";
}
function getData(el, key)
{
return el.dataset[key] ? el.dataset[key].split(",") : [];
}
function addTag(input)
{
const formEl = input.parentNode,
tag = input.value.trim(),
list = formEl.list,
tags = formEl.tags;
if (tag === "" || tags.indexOf(tag) != -1)
return;
const tagsEl = formEl.querySelector(".tags"),
tagEl = document.createElement("span"),
datalistEl = formEl.querySelector("datalist");
if (formEl.dataset.autotags !== undefined && list.indexOf(tag) == -1)
{
const option = document.createElement("option");
option.value = tag;
option.className = "new";
datalistEl.appendChild(option);
list[list.length] = tag;
}
tags[tags.length] = tag;
formEl.list = list;
formEl.tags = tags;
const index = list.indexOf(tag);
datalistEl.children[index].disabled = true;
tagEl.className = "tag";
tagEl.textContent = tag;
tagEl.appendChild(document.createElement("span"));
tagsEl.appendChild(tagEl);
input.value = "";
}
})();
//example:
const test = document.getElementById("test");
test.addEventListener("input", e =>
{
if (e.target !== test)
return;
console.log('value:', test.value);
console.log("tags:", JSON.stringify(test.tags));
console.log("list:", JSON.stringify(test.list));
}, false);
.input-tags
{
display: inline-block;
border: 1px solid black;
font-size: 0.8em;
padding: 0.1em 0.1em 0.1em 0.05em;
width: 100%;
line-height: 1em;
}
.input-tags > input,
.input-tags > input:focus,
.input-tags > input:active
{
outline: none;
border: none;
margin: 0.15em 0;
vertical-align: middle;
max-width: 100%;
box-sizing: border-box;
}
.input-tags > input::-webkit-calendar-picker-indicator
{
display: none !important;
}
.input-tags > .tags
{
vertical-align: middle;
}
.input-tags .tags .tag
{
display: inline-block;
background-color: lightblue;
border: 1px solid blue;
border-radius: 2px;
font-family: "Segoe UI","Liberation Sans",sans-serif;
margin: 0.1em;
padding: 0 0.2em;
line-height: 1.3em;
}
.input-tags .tags .tag > span
{
margin: -0.05em -0.2em 0 0.05em;
cursor: pointer;
display: inline-block;
font-size: 1.3em;
transform: rotate(45deg);
border-radius: 2em;
line-height: 0.7em;
float: right;
}
.input-tags .tags .tag > span:before
{
content: "+";
position: relative;
top: -0.1em;
}
.input-tags .tags .tag > span:hover
{
background-color: #60B3CE;
}
<div style="display: grid; grid-template-columns: auto auto">
<span>Auto-add new tags, suggestions:</span>
<div style="display: inline-block; width: 50vw;">
<div id="test" class="input-tags" data-autotags data-list="test,sometag,SOMETAG,another tag,another tag2,another tag3,another,tag"></div>
</div>
<span>Auto-add new tags, no suggestions:</span>
<div style="display: inline-block; width: 50vw;">
<span class="input-tags" data-autotags></span>
</div>
<span>No new tags, suggestions:</span>
<div style="display: inline-block; min-width: 10em;">
<div class="input-tags" data-list="test,some tag,very long tag,blah"></div>
</div>
<div>
This is a hangman project I'm working on. Inside the guessing function, a for loop is used to add onclick functions to the buttons and another for loop is used to check whether the button's text(a letter) is inside the word. Also a while loop is wrapping these for loops up to check whether the user is out of guesses or he guesses the word. But when I try to run it, browser crashes and I have no clue why it happens.
Also I wonder if I can put the while loop conditions inside the for loop as they works quite similar :/
Here is my code:
window.onload = function() {
var letters = "a b c d e f g h i j k l m n o p q r s t u v w x y z";
var category = ["Premier Leaque Football Teams", "Films", "Cities"];
var wordlist = [
["everton", "liverpool", "swansea", "chelsea", "hull", "manchester-city", "newcastle-united"],
["alien", "dirty-harry", "gladiator", "finding-nemo", "jaws"],
["manchester", "milan", "madrid", "amsterdam", "prague"]
];
var hints = [
["Based in Mersyside", "Based in Mersyside", "First Welsh team to reach the Premier Leauge", "Owned by A russian Billionaire", "Once managed by Phil Brown", "2013 FA Cup runners up", "Gazza's first club"],
["Science-Fiction horror film", "1971 American action film", "Historical drama", "Anamated Fish", "Giant great white shark"],
["Northern city in the UK", "Home of AC and Inter", "Spanish capital", "Netherlands capital", "Czech Republic capital"]
]
var buttons = document.getElementById("buttons");
var showCategory = document.getElementById("show_category");
var hyphens = document.getElementById("hyphens");
var showLives = document.getElementById("show_lives");
var showClue = document.getElementById("show_clue");
var showHint = document.getElementById("show_hint");
var playAgain = document.getElementById("play_again");
letters = letters.split(" ");
var letters_ul = document.createElement("ul");
for (var i = 0; i < letters.length; i++) {
var letters_li = document.createElement("li");
var letters_button = document.createElement("button");
letters_button.innerHTML = letters[i];
letters_li.appendChild(letters_button);
letters_ul.appendChild(letters_li);
}
buttons.appendChild(letters_ul);
initialize = function() {
var c = Math.floor(Math.random() * category.length);
var w = Math.floor(Math.random() * wordlist[c].length);
var word = wordlist[c][w];
var lives = 10;
showCategory.innerHTML = "The Chosen Category is " + category[c];
hyphens.innerHTML = "";
for (var i = 0; i < word.length; i++) {
hyphens.innerHTML += "-";
}
showLives.innerHTML = "You have " + lives + " lives"
showClue.innerHTML = "Clue : -";
showHint.addEventListener("click", function(){
showClue.innerHTML = "Clue : " + hints[c][w];
})
playAgain.addEventListener("click", function(){
initialize();
})
guessing(word, lives);
}
guessing = function(word, lives) {
var button_list = document.querySelectorAll("#buttons ul li button");
var isWord = false;
while (lives > 0 && !isWord) {
for (var i = 0; i < button_list.length; i++) {
button_list[i].addEventListener("click", function(e){
var h = "";
for (var j = 0; j < word.length; j++) {
if (word[j] === e.target.innerHTML) {
h += e.target.innerHTML;
} else if (hyphens.innerHTML[j] === word[j]) {
h += "";
} else {
h += "-";
}
if (hyphens.innerHTML === h && lives > 0) {
lives--;
showLives.innerHTML = "You have " + lives + " lives";
} else if (lives === 0 && !isWord) {
showLives.innerHTML = "Game Over!";
} else if (hyphens.innerHTML === word) {
showLives.innerHTML = "You Win!";
isWord = true;
}
hyphens.innerHTML = h;
}
}
)
}
}
}
initialize();
}
* {
box-sizing: border-box;
}
body {
margin: 0;
background-color: goldenrod;
font-family:'Courier New', Courier, monospace;
text-align: center;
color: white;
}
h1 {
font-size: 50px;
}
h2 {
font-size: 40px;
}
p {
font-size: 25px;
}
#buttons ul {
list-style-type: none;
margin: 0;
padding: 0;
}
#buttons ul li {
display: inline-block;
}
#buttons ul li button {
padding: 10px 15px;
border: 1px solid white;
border-radius: 5px;
background-color: white;
color: goldenrod;
margin: 5px;
}
#buttons ul li button:hover {
background-color: goldenrod;
color: white;
}
#buttons ul li button:active, #buttons ul li button:visited {
opacity: 0.5 !important;
background-color: goldenrod !important;
color: white !important;
}
#hyphens {
font-size: 50px;
}
#hangman {
border: 2px dashed white;
}
.container #show_hint, .container #play_again{
color: white;
background-color: goldenrod;
padding: 20px 40px;
margin: 15px;
border: 1px solid white;
}
.container #show_hint:hover, .container #play_again:hover {
background-color: white;
color: goldenrod;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="hangman">
<meta name="keywords" content="hangman">
<meta name="author" content="Nick Hui">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hangman</title>
<link rel="stylesheet" href="hangman.css">
<script src="hangman.js"></script>
</head>
<body>
<h1>HANGMAN</h1>
<h2>VANILLA JAVASCRIPT HANGMAN GAME</h2>
<p>Use the alphabet below to guess the word, or click hint to get a clue.</p>
<div id="buttons"></div>
<p id="show_category"></p>
<div id="hyphens"></div>
<p id="show_lives">You have 10 lives</p>
<p id="show_clue">Clue: -</p>
<canvas id="hangman"></canvas>
<div class="container">
<button id="show_hint">HINT</button>
<button id="play_again">Play again</button>
</div>
</body>
</html>
I'm new to Cordova, and I'm trying to build an android app
I copied my files into www file and replaced its files with mine
and build apk but when running it on my phone the first two buttons only are working (Equal weight / Unequal weight) while the (add more/ reset/ result buttons ) are not, but when I'm trying to check my code as a web page it works perfectly, as you might see in the snippet
I also tried to keep the cordova.js file and the index.js with my app.js but it didn't work
I tried to add cordova.js and index.js (the files that created automatically when creating a project with Cordova) but it didn't work
//declare the main buttons and divs
const btn1 = document.querySelector('.eqbtn'),
btn2 = document.querySelector('.uneqbtn'),
div1 = document.querySelector('.eqdiv'),
div2 = document.querySelector('.wrap-sub')
div_2 = document.querySelector('.uneqdiv');
//add event listeners to the main buttons
btn1.addEventListener('click', equalFunc);
btn2.addEventListener('click', unequalFunc);
//switch between two keys
function equalFunc() {
togFunc(div1, div_2, btn1, btn2);
resetFunc('.eqdiv', div1);
}
function unequalFunc() {
togFunc(div_2, div1, btn2, btn1);
resetFunc('.wrap-sub', div2);
}
function togFunc(one, two, a, b) {
a.classList.add('active');
b.classList.remove('active');
one.style.display = 'block';
two.style.display = 'none';
}
//declare the equal addmore button
const btnplus = document.querySelector('.eqmore');
const unbtnplus = document.querySelector('.un-eqmore');
//fire when addmore button get fired
btnplus.addEventListener('click', () => {
if (checkIn('.eqdiv') === false) {
errIn();
} else {
creatIn(div1);
}
});
//fire when uneqaddmore get clicked
unbtnplus.addEventListener('click', () => {
if (checkIn('.wrap-sub') === false) {
errIn();
} else {
creatIn(div2);
}
})
//check the value of the inputs
function checkIn(nav) {
let bool;
document.querySelectorAll(`${nav} input`).forEach((elem) => {
if (elem.value === '' || elem.value < 0) {
elem.style.borderColor = '#f86868';
bool = false;
} else {
elem.style.borderColor = '#D1D1D1';
}
});
return bool;
}
//create the input and assign it's value
function creatIn(dnav) {
if (dnav === div1) {
const dive = document.createElement('div');
dive.innerHTML = `<input type ='number'/>`;
dnav.insertBefore(dive, btnplus);
} else {
const sp1 = document.createElement('div'),
sp2 = document.createElement('div');
sp1.innerHTML = `<input type ='number'>`;
sp2.innerHTML = `<input type ='number'>`;
document.querySelector('.div2-1').appendChild(sp2);
document.querySelector('.div2-2').appendChild(sp1);
}
}
//fire an error if the user insert wrong value
function errIn() {
const errdiv = document.createElement('div');
errdiv.innerHTML = `Please fill inputs with positive values`;
errdiv.classList.add('errdiv');
document.querySelector('.wrap').insertAdjacentElement('beforeend', errdiv);
setTimeout(() => errdiv.remove(), 1800);
}
//fire when the reset button get clicked
function resetFunc(x, y) {
document.querySelectorAll(`${x} input`).forEach(reset => {
reset.remove();
});
document.querySelector('#output').innerHTML = '';
creatIn(y);
}
//reset all the inputs
document.querySelector('.reset').addEventListener('click', () => resetFunc('.eqdiv', div1));
document.querySelector('.un-reset').addEventListener('click', () => resetFunc('.wrap-sub', div2));
//fire when result button get fired
document.querySelector('.result').addEventListener('click', resFunc);
document.querySelector('.un-result').addEventListener('click', unresFunc);
//declare result function when result button get clicked
function resFunc() {
if (checkIn('.eqdiv') === false) {
errIn();
} else {
let arr = [];
document.querySelectorAll('.eqdiv input').forEach(res => arr.push(Number(res.value)));
const num = arr.length;
const newarr = arr.reduce((a, b) => a + b);
const mean = newarr / num;
const resarr = [];
arr.forEach(re => resarr.push((re - mean) * (re - mean)));
const newresarr = resarr.reduce((c, v) => c + v);
const norDev = Math.sqrt(newresarr / (num - 1));
const dev = norDev / Math.sqrt(num);
let mpv;
if (!isNaN(dev)) {
mpv = `${mean.toFixed(3)} ± ${dev.toFixed(3)}`;
} else {
mpv = `${mean.toFixed(3)}`;
}
displayResult(mpv);
}
}
function unresFunc() {
if (checkIn('.wrap-sub') === false) {
errIn();
} else {
let allweight = [],
allValues = [],
subMeanArray = [],
sub = [],
semiFinal = [];
document.querySelectorAll('.div2-2 input').forEach(w => allweight.push(Number(w.value)));
const sumWeight = allweight.reduce((n, m) => n + m);
document.querySelectorAll('.div2-1 input').forEach(s => allValues.push(Number(s.value)));
for (i = 0; i < allweight.length; i++) {
subMeanArray.push(allweight[i] * allValues[i]);
}
const sumMean = subMeanArray.reduce((a, b) => a + b);
const mean = sumMean / sumWeight;
allValues.forEach(s => sub.push(s - mean));
for (i = 0; i < allweight.length; i++) {
semiFinal.push(allweight[i] * sub[i] * sub[i]);
}
const alFinal = semiFinal.reduce((a, b) => a + b);
const nDev = Math.sqrt(alFinal / allweight.length);
const Dev = nDev / Math.sqrt(sumWeight);
let mpv;
if (isNaN(Dev)) {
mpv = ` : No choice but the only value you gave which is ${allValues[0].toFixed(3)}`;
} else {
mpv = `${mean.toFixed(3)} ± ${Dev.toFixed(3)}`;
}
displayResult(mpv);
}
}
function displayResult(wow) {
document.querySelector('#output').innerHTML = `The Result is ${wow}`;
}
.wrap>div {
display: none;
}
/* .uneqdiv{
display: none;
} */
.container {
padding-top: 100px;
width: max-content;
padding-bottom: 50px;
}
.wrap {
margin-top: 50px;
}
.wrap-sub {
display: flex;
}
.div2-1 {
margin-right: 5px;
}
button {
outline: none;
transition: border .3s;
}
.active,
.active:focus {
border-color: #46d84d;
}
button.reset:hover,
button.un-reset:hover {
border-color: #f86868;
}
button.eqmore:hover,
button.un-eqmore:hover {
border-color: #46d84d;
}
.errdiv {
height: 40px;
width: 100%;
background-color: #df4f4f;
color: #ffffff;
display: flex !important;
justify-content: center;
align-items: center;
}
#output {
padding-top: 20px;
}
h6 {
margin: 0;
}
.tes {
display: inline-block;
}
#media(max-width: 700px) {
.container {
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
}
.container>h2 {
font-size: 2rem;
}
button {
width: 75%;
max-width: 20rem;
}
.wrap {
display: flex;
flex-direction: column;
align-items: center;
width: 90%;
}
.eqdiv {
text-align: center;
}
.eqdiv input {
max-width: 20rem;
width: 75%;
}
.eqdiv button {
display: block;
margin-left: auto;
margin-right: auto;
}
.uneqdiv {
text-align: center;
width: 100%;
}
.wrap-sub input {
max-width: 25rem;
width: 100%;
}
.uneqdiv .wrap-sub {
width: 100%;
margin-top: 40px;
margin-bottom: 15px;
display: flex;
flex-direction: column;
align-items: center;
}
.wrap-sub h6 {
font-size: 1.4rem;
}
.tes button {
width: 100%;
}
}
<html>
<head>
<meta content="utf-8">
<meta name="viewport" content="initial-scale=1, width=device-width, viewport-fit=cover">
<link rel="stylesheet" type="text/css" href="css/normalize.css">
<link rel="stylesheet" type="text/css" href="css/skeleton.css">
<link rel="stylesheet" type="text/css" href="css/index.css">
<title>survey</title>
</head>
<body>
<div class="container">
<h2 class="jui">Please select the wanted method</h2>
<button class="eqbtn">equal weight</button>
<button class="uneqbtn">unequal weight</button>
<div class="wrap">
<div class="eqdiv">
<h4>Enter the equal values</h4>
<div>
<input type="number" class="init">
</div>
<button class="eqmore">add more +</button>
<button class="reset">reset</button>
<button class="result button-primary">result</button>
</div>
<div class="uneqdiv">
<h4>Enter the unequal values</h4>
<div class="wrap-sub">
<div class="div2-1">
<h6>The Measurements</h6>
<input type="number" class="un-init">
</div>
<div class="div2-2">
<h6>The Weights</h6>
<input type="number" class="un-weight">
</div>
</div>
<div class="tes">
<button class="un-eqmore">add more +</button>
<button class="un-reset">reset</button>
<button class="un-result button-primary">result</button>
</div>
</div>
</div>
<div id="output"></div>
</div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
</html>
Hello guys I hope you can help me with JavaScript, I'm trying to itarate over some divs, the issue is that when I iterate sometimes a div never change to the other divs, it suppose to be infinite, I will recive thousands of different divs with different height and it should create an other div container in the case it does not fits but I can not achieve it work's, I'm using Vanilla JavaScript because I'm lerning JavaScript Regards.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.big_container{
height: 600px;
width: 150px;
background-color: #f1f1f1;
float: left;
}
.items{
background-color: gray;
height: 50px;
}
.new_container{
margin-bottom: 10px;
height: 300px;
width: 150px;
background-color: red;
float: left;
margin-left: 5px;
}
</style>
</head>
<body>
<div class="big_container">
<div class="items">1</div>
<div class="items">2</div>
<div class="items">3</div>
<div class="items">4</div>
<div class="items">5</div>
<div class="items">6</div>
<div class="items">7</div>
<div class="items">8</div>
<div class="items">9</div>
<div class="items">10</div>
<div class="items">11</div>
<div class="items">12</div>
<div class="items">13</div>
</div>
<div class="new_container">
</div>
</body>
<script>
number = 0
sum = 0
new_container = document.getElementsByClassName('new_container')[number].offsetHeight
divs = document.getElementsByClassName('items')
for ( var i = 0; i < divs.length; i++ ){
sum += this.document.getElementsByClassName( 'items' )[0].offsetHeight
if ( sum <= new_container ){
console.log(sum, "yes")
document.getElementsByClassName("new_container")[number].appendChild( this.document.getElementsByClassName( 'items' )[0] )
} else {
sum = 0
console.log(sum, "NO entra")
nuevo_contenedor = document.createElement('div'); // Creo un contenedor
nuevo_contenedor.className = "new_container";
nuevo_contenedor.setAttribute("style", "background-color: red;");
document.body.appendChild(nuevo_contenedor)
number += + 1
}
}
</script>
</html>
I really apreciate a hand.
I know that I'm late, but there is my approach how this can be done.
// generate items with different height
function generateItems(count) {
const arr = [];
for (let i = 0; i < count; i++) {
const div = document.createElement("DIV");
const height = Math.floor((Math.random() * 100) + 10);
div.setAttribute("style", `height: ${height}px`);
div.setAttribute("class", "items");
const t = document.createTextNode(i + 1);
div.appendChild(t);
arr.push(div);
}
return arr;
}
function createNewContainer(height) {
const new_container = document.createElement("DIV")
new_container.setAttribute("class", "new_container");
new_container.setAttribute("style", `height: ${height}px`)
document.body.appendChild(new_container);
return new_container;
}
function breakFrom(sourceContainerId, newContainerHeight) {
const srcContainer = document.getElementById(sourceContainerId);
const items = srcContainer.childNodes;
let new_container = createNewContainer(newContainerHeight);
let sumHeight = 0;
for (let i = 0; i < items.length; i++) {
let item = items[i];
if (item.offsetHeight > newContainerHeight) {
// stop!!! this item too big to fill into new container
throw new Error("Item too big.");
}
if (sumHeight + item.offsetHeight < newContainerHeight) {
// add item to new container
sumHeight += item.offsetHeight;
new_container.appendChild(item.cloneNode(true));
} else {
// create new container
new_container = createNewContainer(newContainerHeight);
new_container.appendChild(item.cloneNode(true));
// don't forget to set sumHeight)
sumHeight = item.offsetHeight;
}
}
// if you want to remove items from big_container
// for (let i = items.length - 1; i >= 0; i--) {
// srcContainer.removeChild(items[i]);
// }
}
// create big container with divs
const big_container = document.getElementById("big_container");
const items = generateItems(13);
items.forEach((div, index) => {
big_container.appendChild(div);
});
breakFrom("big_container", 300);
#big_container {
width: 150px;
background-color: #f1f1f1;
float: left;
}
.items {
background-color: gray;
border: 1px solid #000000;
text-align: center;
}
.new_container {
margin-bottom: 10px;
height: 300px;
width: 150px;
background-color: red;
border: 1px solid red;
float: left;
margin-left: 5px;
}
<div id="big_container"></div>
This example gives you the ability to play with divs of random height. Hope, this will help you.