I'm trying to create a simple app with HTMl, CSS and vanilla JS.
I've got an array, and ant to display its items in a box, with a button below it that gets the average of the array, which should also appear below the button.
So far, the layout has been very difficult, as I'm familiar with core JS and basic HTML, but never worked with scripts before. I can't make the button to be displayed below the array items and in the centre, no matter what I do. For it to appear after the array, I've applied flex box to the body, because I don't know how to create a wrapping html element, although I've seen some threads, don't know how to implement it.
Is there an easy way (avoiding JQuery) of doing this? Can't I just create a wrapping the script?
This is my code so far:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<title>Test</title>
</head>
<body onload="mapping()">
<script>
const array = [2, 3, 4, 5];
function mapping() {
array.map(arrayItem => {
let elements = document.createElement('p');
elements.innerHTML = arrayItem;
document.body.appendChild(elements);
elements.classList.add("numbers");
});
}
</script>
<div class='container'>
<div class='button'>
<p>
<button onClick="average()">Average</button>
</p>
</div>
<div id='val'></div>
</div>
<script>
function average() {
const array = [2, 3, 4, 5]
let count = 0
let val = array.reduce((x, y) => {
if (+y) {
count++
x += +y
}
return x
}, 0)
val = val / count;
document.getElementById('val').innerHTML += val + '<br/>';
}
</script>
</body>
</html>
body {
display: flex;
flex-direction: row-reverse;
justify-content: space-around;
align-items: center;
/* flex-wrap: wrap; */
}
.numbers {
font-size: 5em;
/* color: blue; */
/* text-orientation: unset; */
margin-top: 2em;
}
.button {
padding: 1em;
border: .2em solid red;
margin-top: 20em;
position: inherit;
}
Sorry I'm very junior and can't figure out how to do it.
I'm struggling to fully understand where the issue is, I've gone and made a jsfiddle that I think does what you're interested in.
I have a feeling the problem is the fact that you use display: flex; on the body of the document. I've surrounded the numbers in a separate div element that now has the flex-display options assigned to it.
HTML
const array = [2, 3, 4, 5];
function mapping() {
array.map(arrayItem => {
let elements = document.createElement('p');
elements.innerHTML = arrayItem;
/*
Adding the numbers to the elNumberArray div element in the HTML
*/
document.getElementById("elNumberArray").appendChild(elements);
elements.classList.add("numbers");
});
document.getElementById("elAverageButton").addEventListener("click", average);
}
function average() {
const array = [2, 3, 4, 5]
let count = 0
let val = array.reduce((x, y) => {
if (+y) {
count++
x += +y
}
return x
}, 0)
val = val / count;
document.getElementById('val').innerHTML += val + '<br/>';
}
document.onload = mapping();
body {}
/* display-flex settings are now no longer on the whole body
but set for elNumberArray div element */
#elNumberArray {
display: flex;
flex-direction: row-reverse;
justify-content: space-around;
align-items: center;
/* flex-wrap: wrap; */
}
.numbers {
font-size: 5em;
/* color: blue; */
/* text-orientation: unset; */
margin-top: 2em;
}
.button {
padding: 1em;
border: .2em solid red;
margin-top: 20em;
position: inherit;
}
<div id="elNumberArray">
<!--Numbers are now inserted here-->
</div>
<div class='container'>
<div class='button'>
<p>
<button id="elAverageButton">Average</button>
</p>
</div>
<div id='val'></div>
</div>
The button and average are now displayed below the numbers.
Is this what you were looking for?
You should place the array contents inside span tags instead of p tags.
body {
display: flex;
align-items: center;
/* flex-wrap: wrap; */
}
.numbers {
font-size: 5em;
}
.button {
padding: 1em;
border: .2em solid red;
margin-top: 20em;
}
.container{
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<title>Test</title>
</head>
<body onload="mapping()">
<script>
const array = [2, 3, 4, 5];
function mapping() {
array.map(arrayItem => {
let elements = document.createElement('span');
elements.innerHTML = arrayItem;
document.getElementById("numbers").appendChild(elements);
elements.classList.add("numbers");
});
}
</script>
<span id="numbers" style="margin: 20px;">
</span>
<div class='container'>
<div class='button'>
<p>
<button onClick="average()">Average</button>
</p>
</div>
<div id='val'></div>
</div>
<script>
function average() {
const array = [2, 3, 4, 5]
let count = 0
let val = array.reduce((x, y) => {
if (+y) {
count++
x += +y
}
return x
}, 0)
val = val / count;
document.getElementById('val').innerHTML += val + '<br/>';
}
</script>
</body>
</html>
JSFiddle: http://jsfiddle.net/kru10xgd/11/
const array = [2, 3, 4, 5];
let arrayContainer = document.getElementById('arrayContainer');
(function mapping() {
array.map(arrayItem => {
let element = document.createElement('p');
element.innerHTML = arrayItem;
element.classList.add("numbers");
arrayContainer.appendChild(element);
});
})();
function average() {
let count = 0
let val = array.reduce((x, y) => {
if (+y) {
count++
x += +y
}
return x
}, 0)
val = val / count;
document.getElementById('val').innerHTML += val + '<br/>';
}
.container {
width: 50%;
margin: 0 auto;
text-align: center;
transform: translate(-50%, -50%);
position: absolute;
top: 50%;
left: 50%;
}
#arrayContainer {
display: flex;
justify-content: space-evenly;
border: 1px solid;
}
.numbers {
min-width: 20px;
}
.button {
margin: 20px 0px;
}
<div class='container'>
<div id="arrayContainer"></div>
<div class='button'>
<button onClick="average()">Average</button>
</div>
<div id='val'></div>
</div>
Something like this maybe , you are trying to achieve?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- // <link rel="stylesheet" href="style.css"> -->
<title>Test</title>
<style>
.container{
width: 50%;
margin: 0 auto;
text-align: center;
transform: translate(-50%,-50%);
position: absolute;
top: 50%;
left: 50%;
}
#arrayContainer{
display: flex;
justify-content: space-evenly;
border: 1px solid;
}
.numbers {
min-width: 20px;
}
.button {
margin: 20px 0px;
}
</style>
</head>
<body>
<div class='container'>
<div id="arrayContainer"></div>
<div class='button'>
<button onClick="average()">Average</button>
</div>
<div id='val'></div>
</div>
<script>
const array = [2, 3, 4, 5];
let arrayContainer = document.getElementById('arrayContainer');
(function mapping() {
array.map(arrayItem => {
let element = document.createElement('p');
element.innerHTML = arrayItem;
element.classList.add("numbers");
arrayContainer.appendChild(element);
});
})();
function average() {
let count = 0
let val = array.reduce((x, y) => {
if (+y) {
count++
x += +y
}
return x
}, 0)
val = val / count;
document.getElementById('val').innerHTML += val + '<br/>';
}
</script>
</body>
</html>
Related
![Text](https://stackoverfl
var obj = {
count: 1
}
function elementSet()
{
if(obj.count=1){
document.getElementById("text").textContent = "graa";}
if(obj.count=2){
document.getElementById("text").textContent = "graa";}
if(obj.count=3){
document.getElementById("text").textContent = "graa";}
}
function back()
{
if(obj.count>1)
{
obj.count = obj.count -1;
document.getElementById("back").style.display = "block";
document.getElementById("page_num").textContent = obj.count;
}
}
function forth()
{
if(obj.count<3){
obj.count = obj.count +1;
document.getElementById("page_num").textContent = obj.count;
document.getElementById("forth").style.display = "block";
if (obj.count>3){
document.getElementById("forth").style.display = "none";}
}
}
.colx1 {
color: #e1992e;
/* height: 3px; */
font-size: 2.1ch;
margin-right: 80%;
inline-size: auto;
border-color: #e1992e;
border-radius: 11ch;
}
.colx2 {
color: #e1992e;
font-size: 2.1ch;
inline-size: auto;
margin-top: -3%;
margin-left: 80%;
border-color: #e1992e;
border-radius: 11ch;
}
.colabount
{
width: 170px;
}
.row {
display: inline;
}
.body
{
text-align: center;
max-height: 100%;
}
.button {
border-color: #e1992e;
}
.page_num
{
color: black;
size: 13ch;
text-align: center;
}
.text
{
color: blanchedalmond;
size: 12ch;
}
<!DOCTYPE html>
<html>
<head>
<title>films</title>
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body class="body">
<div class="container external internal" id="content">
<h2 id="text" class="text" type="textContent"> its the f</h2>
<div class="row">
<button class="colx1" id="back" type="button" onclick="back(),elementSet()"><b>back</d></button>
<button class="colx2" id="forth" type="button" onclick="forth(),elementSet()"><b>forth</d></button>
</div>
<div class="page_num"><b id ="page_num">1</b></div>
</div>
</body>
</html>
ow.com/image.jpg)
i tried to create external obj that contain count its working.
the page content will change acording to the count number.
the proble starts when im calling 'elementSet' = {checking abount obj.count and
changing the page acordingly}
THE PROBLEM : when elementSet runs back() and forth() not working anymore!
your mistake is that:
in java script = is assignment. for example: let a = 0;
we assignment 0 to a. now a is 0.
and we have == and ===. these are use for comparison in logics and Condition. for example:
let a = 0;
a == 0 && console.log("yes");
there are some different between == and ===. you can read that in a link!
im trying to make static grid with a button that can change number of boxes in it (from 16x16 to 64x64 and anything between). Grid is 40rem x 40rem, when i try to change manually number of boxes in makeGrid() function it works fine up to 20 (boxes change size accordingly), but anything above 20 stays the same size and gets cutoff from my grid. If there is no grid css overflow property stated, grid width change depending on number of boxes but boxes themself won't shrink
my code:
size button is not working yet, grid size need to be changed mannualy in makeGrid function
const grid = document.getElementById('grid');
const size = document.getElementById('size');
const eraser = document.getElementById('eraser');
const color = document.getElementById('color');
const gridBorder = document.getElementById('grid-borders');
const clear = document.getElementById('clear');
// grid
function makeGrid(number) {
number = number || 16;
let cellWidth = 40 / number + 'rem';
let cellHeight = 40 / number + 'rem';
grid.style.gridTemplateColumns = `repeat( ${number}, 1fr)`;
grid.style.gridTemplateRows = `repeat(${number}, 1fr)`;
for (let i = 0; i < number * number; i++) {
let cell = document.createElement('div');
grid.appendChild(cell).id = 'box';
cell.classList.add('border');
cell.classList.add('box');
cell.style.backgroundColor = 'white';
cell.style.width = cellWidth;
cell.style.height = cellHeight;
}
size.textContent = `${number} x ${number}`;
}
makeGrid();
// drawing on hover
color.addEventListener('click', function () {
grid.addEventListener('mouseover', function (e) {
e.target !== grid ? (e.target.style.backgroundColor = 'black') : null;
});
});
function changeColor(event) {
event.target.style.backgroundColor = 'black';
}
// erase functionality
eraser.addEventListener('click', function () {
grid.addEventListener('mouseover', function (e) {
e.target !== grid ? (e.target.style.backgroundColor = 'white') : null;
});
});
// grid borders
const allBoxes = document.querySelectorAll('.box');
gridBorder.addEventListener('click', function () {
allBoxes.forEach((box) => {
box.classList.toggle('no-border');
box.classList.toggle('border');
});
});
// clear button
clear.addEventListener('click', function () {
allBoxes.forEach((box) => {
box.style.backgroundColor = 'white';
});
});
// size button
// size.addEventListener('click', function () {
// let number = prompt(`Enter grid size less or equal to 100`);
// if (number !== Number.isInteger()) {
// return;
// } else if (number > 100) {
// number = prompt(`Enter grid size greater or equal to 100`);
// }
// });
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
height: 100vh;
background-color: aquamarine;
}
#grid {
display: grid;
justify-content: center;
border: 1px solid #ccc;
width: 40rem;
height: 40rem;
min-width: 0;
min-height: 0;
overflow: hidden;
}
.box {
padding: 1em;
}
#title {
display: flex;
align-items: flex-end;
justify-content: center;
height: 180px;
}
#container {
display: flex;
height: 60%;
width: 1259px;
align-items: flex-start;
justify-content: flex-end;
gap: 20px;
padding-top: 20px;
}
#menu {
display: flex;
flex-direction: column;
gap: 10px;
}
.border {
outline: 1px solid black;
}
.no-border {
outline: none;
}
.black-bg {
background: black;
}
.white-bg {
background: white;
}
<!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>Etch-a-Sketch</title>
<link rel="stylesheet" href="style.css" />
<script src="script.js" defer></script>
</head>
<body>
<div id="title">
<h1>Etch-a-Sketch</h1>
</div>
<main id="container">
<div id="menu">
<button id="size"></button>
<button id="color">Color</button>
<button id="eraser">Eraser</button>
<button id="clear">Clear</button>
<button id="grid-borders">Grid Borders</button>
</div>
<div id="grid"></div>
</main>
</body>
</html>
"Why won't my grid cells go below 32px?" - have you checked your padding (hint: 32px is exactly equal to 2 * 16px which in turn is exactly equal to your padding of 1em with most browsers implementing a default font-size of 16px). –
David Thomas
box padding was set to 1em which caused my problem, after deleting it my grid worked as intended
I'm doing a project to make an etch-a-sketch every time I hover on the grid. What I'm trying to do is to make a button to clear up all the colors made.
The sketch picture.
I guess what I need to do is to remove the style elements while clicking the button. But I'm just note sure how to link the button with the style elements.
const container = document.querySelector(".container");
// const table = document.createElement('div');
// table.classList.add('grid-square');
// table.textContent = 'hello';
// container.appendChild(table);
function makeTable(rows, cols) {
container.style.setProperty('--grid-rows', rows);
container.style.setProperty('--grid-cols', cols);
for (i = 0; i < (rows * cols); i++){
const cell = document.createElement('div');
// cell.innerText = (i + 1);
container.appendChild(cell).className = "table";
};
};
makeTable(16, 16);
// const container = document.querySelector('.container')
const grids = document.querySelectorAll('.table')
grids.forEach(element => {
element.addEventListener('mouseover', (e) => {
e.target.style.backgroundColor = randomColor();
console.log(e)
})
});
function randomColor() {
var generateColor = '#' + Math.floor(Math.random()*16777215).toString(16);
return generateColor;
}
function resizeGrid() {
sketchSize = prompt("Enter 1 to 100 to resize sketch");
return sketchSize;
}
// const button = document.querySelector('button')
// button.addEventListener('click', (e) => {
// });
:root {
--grid-rows: 1;
--grid-cols: 1;
}
.container {
display: grid;
/* grid-gap: 1em; */
grid-template-rows: repeat(var(--grid-rows), 1fr);
grid-template-columns: repeat(var(--grid-cols), 1fr);
/* border: 1px solid black; */
width: 50%;
size: 960px;
}
.table {
padding: 1em;
border: 1px solid coral;
text-align: center;
/* border: none; */
}
header {
display: flex;
justify-content: center;
margin: 20px;
gap: 10px;
}
<!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>Etch-A-Sketch</title>
<script src="index.js" defer></script>
<link rel="stylesheet" href="index.css">
</head>
<body>
<header>
<button class="clear-button">Clear</button>
<button class="resize">Resize</button>
</header>
<div class="container"></div>
</body>
</html>
Cheers!!
To answer my own question, I figured how to do it.
const clear = document.querySelector('.clear-button')
clear.addEventListener('click', () => {
grids.forEach(element => {
element.style.backgroundColor = null;
})
})
I was struggling earlier because I'm not sure how to put other elements (e.g. grids) to the new eventListener.
I want to create one slide show with Array. I created the "next" button and this works good.
I tried to fix the "prv" button but I can't. What to do? I tried imgIndex--; but its not working.
let downimgs = document.querySelectorAll('.down-imgs img')
let topimg = document.querySelector('.top-img img')
let myImg = document.getElementById('mainimge')
let imgArray = ["img/3-kid.jpeg", "img/men-1.jpg", "img/woamn-1.jpeg", "img/woman-2.jpg"]
let imgIndex = 0;
downimgs.forEach(imgs => {
imgs.addEventListener('click', () => {
topimg.src = imgs.src
})
});
function next() {
myImg.setAttribute("src", imgArray[imgIndex]);
imgIndex++;
if (imgIndex >= imgArray.length) {
imgIndex = 0
}
}
// my proplem here ..
function prv() {
myImg.setAttribute("src", imgArray[imgIndex - 1]);
imgIndex--;
if (imgIndex >= imgArray.length) {
imgIndex = 3
}
}
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
img {
height: 300px;
}
.top-img img {
width: 100%;
object-fit: cover;
position: relative;
}
.next,
.prv {
display: inline-block;
width: 150px;
height: 150px;
left: 100%;
position: absolute;
padding: 15px;
font-size: 50px;
color: red;
cursor: pointer;
}
.next {
transform: translate(-150px, -50px);
}
.prv {
left: 0;
transform: translate(150px, -50px);
}
.down-imgs img {
width: 150px;
height: 150px;
}
.full-parent {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
<!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="s.css">
</head>
<body>
<section class="full-parent">
<figure class="top-img">
<img src="img/3-kid.jpeg" alt="" id="mainimge">
</figure>
<div class="down-imgs">
<img src="img/3-kid.jpeg" class="slide">
<img src="img/men-1.jpg" alt="" class="slide">
<img src="img/woamn-1.jpeg" alt="" class="slide">
<img src="img/woman-2.jpg" alt="" class="slide">
</div>
<span class="next" onclick="next()">❯</span>
<span class="prv" onclick="prv()">❮</span>
</section>
<script src="s.js"></script>
</body>
</html>
There is a defect in your prv function. You are decrementing imgIndex, but then checking that imgIndex is greater than or equal to the array length. Instead, you want to check that imgIndex is less than 0, then adjust accordingly. You will also want to change the order of the boundary check, otherwise you have potential to go out of bounds with imgArray[imgIndex-1].
Based on your code, I believe you want something like:
function prv(){
if (--imgIndex<0){ // if imgIndex leaves imgArray lower bound
imgIndex = imgArray.length-1; // wrap imgIndex around to the upper bound of the array
}
myImg.setAttribute("src" , imgArray[imgIndex]);
}
I would like to capture data from selected div(ie. name of country) by click and put in span , additionaly i want to find some way to mark selected divs, but also unmark others div which were selected previously.
https://codepen.io/tatasek/pen/PoojNGL
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div class="div div__first"></div>
<div class="div div__second"></div>
<div class="div div__third"></div>
<p>I have selected:<span class="selectedCountry"></span></p>
<script src="app.js"></script>
</body>
</html>
CSS
body{
display: flex;
height: 100vh;
justify-content: center;
align-items: center;;
}
.div{
margin-left: 10px;
padding: 3px;
border: 2px solid black;
background-color: skyblue;
cursor: pointer;
}
p{
margin-left: 10px;;
}
.active{
background-color: yellow;
}
JS
const countries = ['Lithuania', 'Latvia', 'Estonia'];
const divList = document.querySelectorAll('.div');
divList.forEach(function(div, index){
div.textContent = countries[index];
})
Thanks for your time!
Michal
Building on what you've done so far, I just added some event listeners to check for changes and add the selected items to the list. Let me know if you need any further clarification.
const countries = ['Lithuania', 'Latvia', 'Estonia'];
const divList = document.querySelectorAll('.div');
divList.forEach(function(div, index){
div.textContent = countries[index];
div.addEventListener('click', function(){
divList.forEach(function(el, i) {
el.classList.remove('active')
})
this.classList.toggle('active');
})
})
var choices = document.getElementsByTagName('div')
for(var i = 0; i < choices.length; i++) {
choices[i].addEventListener('click', function() {
document.getElementsByClassName('selectedCountry')[0].innerText =
document.getElementsByClassName('active')[0].innerText;
})
}
body{
display: flex;
height: 100vh;
justify-content: center;
align-items: center;
}
.div{
margin-left: 10px;
padding: 15px;
border: 2px solid black;
background-color: skyblue;
cursor: pointer;
}
p{
margin-left: 10px;
}
.active{
background-color: yellow;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div class="div div__first"></div>
<div class="div div__second"></div>
<div class="div div__third"></div>
<p>I have selected:<span class="selectedCountry"></span></p>
<script src="app.js"></script>
</body>
</html>
Try
for (let i = 0; i < document.getElementsByClassName('div').length; i++) {
document.getElementsByClassName('div')[i].addEventListener('click', appendToSpan, false);
}
function appendToSpan(e) {
document.getElementsByClassName('selectedCountry')[0].innerText += e.target.innerText;
}
Edit:
Change to:
const countries = ['Lithuania', 'Latvia', 'Estonia'];
const divList = document.querySelectorAll('.div');
divList.forEach(function(div, index){
div.textContent = countries[index];
div.addEventListener('click', function() {
this.classList.toggle('active');
if (this.classList.contains('active')) {
document.getElementsByClassName('selectedCountry')[0].classList.add(this.innerText);
} else {
document.getElementsByClassName('selectedCountry')[0].classList.remove(this.innerText);
}
let classes = document.getElementsByClassName('selectedCountry')[0].getAttribute('class').split(' ');
document.getElementsByClassName('selectedCountry')[0].innerText = '';
for (let i = 1; i < classes.length; i++) {
document.getElementsByClassName('selectedCountry')[0].innerText += classes[i]
}
})
})
I've used addEventListener on click event on each div. Also I've created selected variable which is an array and keeps selected items. On click I check if the selected value is in selected variable by indexOf() function which returns -1 if there is not. Then I push() value to the array if it's not selected yet or delete it by splice() and index of value.
Array is printed by join() function which concats each value of array,
const divList = document.querySelectorAll('.div');
const output = document.querySelector('.selectedCountry');
const countries = ['Lithuania', 'Latvia', 'Estonia'];
let selected = [];
divList.forEach((div, index) => {
div.textContent = countries[index];
div.addEventListener('click',()=> {
var indexOfDiv = selected.indexOf(countries[index]);
(indexOfDiv >= 0)
? (selected.splice(indexOfDiv,1) && div.classList.remove('selected'))
: (selected.push(div.textContent) && div.classList.add('selected'))
output.textContent = selected.join(', ');
});
});
.div { border: 1px solid lightgray; margin: 0.5rem; padding: 0.25rem 0.4rem; }
.div.selected { border-color: lightgreen; }
<div class="div div__first"></div>
<div class="div div__second"></div>
<div class="div div__third"></div>
<p>I have selected:<span class="selectedCountry"></span></p>
const countries = ['Lithuania', 'Latvia', 'Estonia'];
const divList = document.querySelectorAll('.div');
const selectedCountry = document.getElementsByClassName('selectedCountry')[0];
function clearSelection() {
divList.forEach(function(div) {
div.classList.remove('active');
})
}
divList.forEach(function(div, index){
div.textContent = countries[index];
div.addEventListener('click', function() {
clearSelection();
this.classList.add('active');
selectedCountry.innerText = document.getElementsByClassName('active')[0].innerText;
})
})
body{
display: flex;
height: 100vh;
justify-content: center;
align-items: center;
}
.div{
margin-left: 10px;
padding: 15px;
border: 2px solid black;
background-color: skyblue;
cursor: pointer;
}
p{
margin-left: 10px;
}
.active{
background-color: yellow;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div class="div"></div>
<div class="div"></div>
<div class="div"></div>
<p>I have selected:<span class="selectedCountry"></span></p>
<script src="app.js"></script>
</body>
</html>