I created an array with four objects. I am attempting to show a new random object in the array each time a button (HAPPY) is clicked, using a FOR loop. However, on button click, the loop only runs once with no error messages given. I have looked through other peoples' for loops and they are similar or identical to mine. So I am not sure where I have gone wrong.
I know that a small part of code is missing to bring everything together. I suspected it was something to do with [i] and have tried adding this to different parts of the code - to no avail.
Any help appreciated, thank you. JS Fiddle HERE
window.onload = () => {
/* HTML ELEMENTS */
var arrow = document.getElementById("arrow");
var welcomeButton = document.getElementById("welcome-button");
var welcomeBox = document.getElementById("welcome-box");
var introQuestion = document.getElementById("intro-question");
var happyButton = document.getElementById("happy");
const nextVerseButton = document.querySelector(".box-button");
const slider = document.querySelector(".happy-slider");
const bibleBox = document.querySelector(".happy-bible-box");
var pageTitle = document.getElementById("title");
var pageVerse = document.getElementById("verse");
const happyVerses = [{
title: "Psalm 28:7",
verse: "The Lord is my strength and shield. I trust him with all my heart. He helps me, and my heart is filled with joy.I burst out in songs of thanksgiving."
},
{
title: "Philippians 4:4",
verse: "Rejoice in the Lord always. Again I will say, rejoice!"
},
{
title: "John 15:11",
verse: "These things have I spoken to you, that My joy may remain in you, and that your joy may be full."
},
{
title: "2 Corinthians 6:10",
verse: "Our hearts ache, but we always have joy. We are poor, but we give spiritual riches to others.We own nothing, and yet we have everything."
},
];
console.log(happyVerses);
// Random verse
const randomVerse = happyVerses[Math.floor(Math.random() * happyVerses.length)];
let newTitle = randomVerse.title;
let newVerse = randomVerse.verse;
welcomeButton.onclick = () => {
welcomeBox.style.display = "none";
introQuestion.style.display = "flex";
}
happyButton.onclick = () => {
introQuestion.style.display = "none";
arrow.style.display = "block";
bibleBox.style.display = "block";
}
arrow.onclick = () => {
arrow.style.display = "none";
introQuestion.style.display = "flex";
bibleBox.style.display = "none";
}
changeText = () => {
pageTitle.innerHTML = newTitle;
pageVerse.innerHTML = newVerse;
}
nextVerseButton.onclick = () => {
for (i = 0; i < happyVerses.length; i++) {
changeText();
};
i++;
}
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
outline: none;
-webkit-transform-style: preserve-3d;
-webkit-backface-visibility: hidden;
}
.fade {
transition: ease 0.3s;
opacity: 0;
}
button {
cursor: pointer;
transition: ease 0.3s;
}
button:hover {
background-color: white !important;
color: black !important;
transform: scale(1.1, 1.1);
}
.page-wrap {
width: 1000px;
max-width: 100%;
/*Wrapper width*/
margin-left: 5%;
/*Nice space between content and device border*/
margin-right: 5%;
/*Nice space between content and device border*/
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
height: 500px;
position: relative;
}
#arrow {
align-self: flex-start;
position: absolute;
top: 0;
font-size: 2em;
color: white;
display: none;
cursor: pointer;
}
#header-2 {
width: 100%;
height: 100px;
display: flex;
justify-content: center;
align-items: center;
}
#header-2 h1 {
color: white;
}
main {
width: 100%;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
background-color: #0E7CFF;
}
#main-wrap {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
#welcome-box {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
#welcome h1 {
color: white;
margin-bottom: 12px;
}
#welcome-button {
padding: 12px 30px 12px 30px;
border: solid 1.5px white;
border-radius: 50px;
background-color: transparent;
color: white;
}
#button-div {
display: flex;
flex-direction: column;
display: flex;
justify-content: space-evenly;
max-width: 300px;
width: 100%;
}
#button-div button {
margin-top: 20px;
margin-bottom: 20px;
padding: 12px;
}
#intro-question {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
display: none;
}
#intro-question button {
padding: 12px;
border: solid 1.5px white;
border-radius: 50px;
background-color: transparent;
color: white;
}
#intro-question button:nth-child(1) {
margin-top: 0;
}
#intro-question button:nth-child(4) {
margin-bottom: 0;
}
#intro-question h1 {
font-size: 2em;
margin-bottom: 50px;
}
.happy-bible-box {
color: white;
max-width: 500px;
width: 100%;
display: none;
transition: ease 0.3s;
}
#title {
font-family: 'Baloo Bhaina 2', cursive;
font-weight: 400;
}
.happy-bible-box p {
margin-top: 12px;
margin-bottom: 30px;
font-family: 'Baloo Bhaina 2', cursive;
transition: all 0.5s;
}
.box-button {
padding-left: 20px;
padding-right: 20px;
padding-top: 10px;
padding-bottom: 10px;
border: solid 1.5px white;
border-radius: 50px;
background-color: transparent;
color: white;
font-family: 'Baloo Bhaina 2', cursive;
}
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Bible</title>
<script src="script.js"></script>
<script src="https://kit.fontawesome.com/cd801faa65.js" crossorigin="anonymous"></script>
<link href="https://fonts.googleapis.com/css?family=Baloo+Bhaina+2:400,500&display=swap" rel="stylesheet">
</head>
<body>
<main id="main">
<div class="page-wrap">
<i class="fa fa-angle-left" id="arrow"></i>
<div id="welcome-box">
<h1>Welcome to Bible</h1>
<button id="welcome-button">Let's go</button>
</div>
<div id="intro-question">
<h1>How are you feeling today?</h1>
<div id="button-div">
<button id="happy">Happy</button>
<button id="anxious">Anxious</button>
<button id="worried">Worried</button>
<button id="lustful">Confused</button>
</div>
</div>
<article class="happy-bible-box">
<h2 id="title">John 15:11</h2>
<p id="verse">These things have I spoken to you, that My joy may remain in you, and that your joy may be full.</p>
<button class="box-button">Show me another</button>
</article>
</div>
You get random verse for once :
let randomVerse = happyVerses[Math.floor(Math.random()*happyVerses.length)];
let newTitle = randomVerse.title;
let newVerse = randomVerse.verse;
Put this in the changetext function to get random verse every time.
Like this:
changeText = () => {
let randomVerse = happyVerses[Math.floor(Math.random()*happyVerses.length)];
pageTitle.innerHTML = randomVerse.title;
pageVerse.innerHTML = randomVerse.verse;
}
You have to put the randomVerse into changeText() function to get it executed everytime nextVerseButton is clicked
You don't need to for loop, just run the change function: changeText();
Your logic is a little confused. You need to get another random verse, your for loop is currently just setting the same thing everytime
nextVerseButton.onclick = () => {
let randomVerse = happyVerses[Math.floor(Math.random()*happyVerses.length)];
let newTitle = randomVerse.title;
let newVerse = randomVerse.verse;
changeText();
}
Related
// GET
const getAdviceNumber = document.querySelector('#adviceNumber');
const adviceResultsDiv = document.querySelector('#adviceResults');
const diceBtn = document.querySelector('#spinDice');
const staticText = document.querySelector('#static');
const favouriteSection = document.querySelector('.favouriteSection')
diceBtn.addEventListener('click', () => {
const getAPI = async () => {
// Call API
/* eslint-disable */
const res = await axios.get('https://api.adviceslip.com/advice');
// remove static text
staticText.remove();
// Generate spin on btn
const element = document.querySelector('#spinDice');
element.classList.add('rotateMe');
setTimeout(() => element.classList.remove('rotateMe'), 800);
// generate unique id number
const header = document.createElement('h1');
header.className = 'title';
header.append(` ADVICE # ${res.data.slip.id}`);
while (getAdviceNumber.childElementCount > 0) {
getAdviceNumber.firstChild.remove();
}
getAdviceNumber.append(header);
// generate unique advice
const para = document.createElement('p');
para.className = 'para';
para.append(`"${res.data.slip.advice}"`);
while (adviceResultsDiv.childElementCount > 0) {
adviceResultsDiv.firstChild.remove();
}
adviceResultsDiv.append(para);
//generate add to favourites button
const addFavourite = document.createElement('p');
addFavourite.className = 'fav';
addFavourite.innerHTML = `<p>Add to Favourites<i class="fa-solid fa-folder-plus"></i></p>`;
while (favouriteSection.childElementCount > 0) {
favouriteSection.firstChild.remove();
}
favouriteSection.append(addFavourite)
};
getAPI();
favouriteSection.addEventListener('click', () => {
const favouriteItem = document.createElement('p');
favouriteItem.innerHTML = `<p class="icons"><i class="fa-solid fa-magnifying-glass"></i> <i class="fa-solid fa-trash-can"></i></p>`
favouriteItem.className = 'favouriteItemBorder';
favouriteSection.append(favouriteItem)
favouriteItem.append(`${getAdviceNumber.textContent}: ${ adviceResultsDiv.textContent}`)
})
});
body {
background-color: hsl(218, 23%, 16%);
font-family: Arial, Helvetica, sans-serif;
}
#advice-container {
background-color: hsl(217, 19%, 38%);
border-radius: 20px;
position: absolute;
-ms-transform: translateY(-50%);
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 300px;
padding-bottom: 40px;
}
h2 {
color: hsl(193, 38%, 86%);
text-align: center;
}
.title {
color: hsl(150, 100%, 66%);
font-size: 15px;
text-align: center;
margin-top: 20px;
}
.para {
color: hsl(193, 38%, 86%);
font-size: 28px;
font-weight: 500;
text-align: center;
margin: 20px 20px 0 20px;
}
.btn {
margin-top: 40px;
margin-bottom: -75px;
}
.dice-container {
background-color: hsl(150, 100%, 66%);
border: solid 2px hsl(193, 38%, 86%);
border-radius: 33px;
margin: 20px 110px 0 110px;
}
.dice-container:hover {
box-shadow: 0 0 30px -2px #52ffa8;
}
.fa-dice-five {
font-size: 50px;
width: 100%;
text-align: center;
padding-top: 10px;
padding-bottom: 10px;
padding-right: 10px;
/* transform: rotate(90deg); */
}
.rotate {
transition: all 0s ease;
transform: rotate(0deg);
}
.rotateMe {
transition: all 0.3s ease;
transform: rotate(90deg);
}
#icons {
color: hsl(193, 38%, 86%);
}
.icon-container {
padding: 20px 120px 0 120px;
width: 100%;
}
.fa-grip-lines-vertical {
margin: 0 10px 0 10px;
}
.line {
width: 100%;
}
.favouriteSection {
position: absolute;
top: 70%;
}
.fav {
color: #52ffa8;
font-size: 32px;
margin: 20px;
}
.fa-folder-plus {
margin-left: 10px;
}
.favouriteItemBorder {
border: 2px solid white;
width: 300px;
height: 60px;
margin: 20px;
padding: 10px;
text-align: center;
}
.icons {
position:absolute;
bottom:10px;
left: 40%;
font-size: 20px;
}
/* desktop ..................................................................................... */
#media screen and (min-width: 720px) {
#advice-container {
display: flex;
width: 900px;
flex-direction: column;
justify-content: space-between;
align-items: center;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- displays site properly based on user's device -->
<title>Oshane| Advice generator app</title>
<link rel="stylesheet" href="style.css">
<script src="https://kit.fontawesome.com/030a66e167.js" crossorigin="anonymous"></script>
</head>
<body>
<section id="advice-container">
<div id="static">
<h2>Click the Dice Button <br><br> below <br><br> to get advice</h2>
</div>
<div id="adviceNumber"> </div>
<div id="adviceResults"></div>
<div class="btn" id="getDataBtn">
<button id="spinDice" class="dice-container rotate" type="submit"><i class="fa-solid fa-dice-five"></i></button>
</div>
</section>
<section class="favouriteSection">
</section>
<!-- <script src="./node_modules/axios/dist/axios.min.js"></script> -->
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="app.js"></script>
</body>
</html>
]2]2how can I prevent this from adding the same text each time the add favourite icon is clicked? It should just add it once and if the add favourite btn is selected again and the quote already exists it should not repeat adding the same ones. I tried a few stuff but as I am a beginner those did not work.
Please anyone can assist?
You can check for something before adding/pushing into favorites array.
Check if something like id(best) or string exists in the arrray and if so - return, else push
Step by step, this is what you are missing:
Create an empty object.
Each time the user clicks the "Add to Favourites" button, you should check if it's already in that object.
If it is, you are done handling that click event.
If it is not, you should add it to the object and then proceed with the logic you currently have to update the UI.
Simplified example:
const rollButton = document.getElementById('roll');
const numberElement = document.getElementById('number');
const addToFavouritesButton = document.getElementById('addToFavourites');
const favouritesElement = document.getElementById('favourites');
let number = null;
rollButton.addEventListener('click', () => {
numberElement.textContent = number = Math.floor(Math.random() * 10);
addToFavouritesButton.removeAttribute('disabled');
});
const favourites = {};
addToFavouritesButton.addEventListener('click', () => {
if (favourites[number]) return;
favourites[number] = true;
favouritesElement.textContent = Object.keys(favourites).sort((a, b) => a - b).join(', ');
if (Object.keys(favourites).length === 10) {
numberElement.textContent = '🎉';
rollButton.setAttribute('disabled', true);
addToFavouritesButton.setAttribute('disabled', true);
}
});
body,
button {
font-family: monospace;
}
p {
text-align: center;
}
button {
border: 3px solid black;
border-radius: 4px;
background: transparent;
padding: 8px 16px;
}
button:hover {
background: yellow;
}
button:disabled {
border-color: #CCC;
color: #CCC;
background: transparent;
}
#number {
border: 3px solid black;
width: 48px;
height: 48px;
display: inline-flex;
align-items: center;
justify-content: center;
border-radius: 4px;
}
#favourites {
display: inline-flex;
align-items: center;
justify-content: center;
border: 3px solid black;
border-radius: 4px;
background: transparent;
padding: 8px 16px;
}
<p>
<button id="roll">🎲 Roll Dice</button>
<button id="addToFavourites" disabled>⭐ Add to Favourites</button>
</p>
<p>
<span id="number">?</span>
</p>
<p>
<span id="favourites"> </span>
</p>
I am trying to insert an HTML element (in my file it is called "baseketTotal"). This element is something like a checkout form that has the total price and etc... The thing is that I am trying to put it only on the last movie in the list which I add to the bag.
In this link, it is a picture of how it looks now. So I need to display it only on the last movie, no matter if the list has 1,2, or 10 movies. Only on the last one.
HTML
<!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" />
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD#48,400,0,0"
/>
<link rel="stylesheet" href="style.css" />
<title>Filmovizija</title>
</head>
<body>
<h1>Filmovizija</h1>
<div class="prozor"></div>
<h2>Shooping bag</h2>
<div class="shooping-cart"></div>
<script src="script.js"></script>
</body>
</html>
css
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background-color: #22254b;
font-family: "Poppins", sans-serif;
}
h1 {
text-align: center;
color: #eee;
font-family: inherit;
margin-top: 30px;
margin-bottom: 30px;
}
.prozor {
display: flex;
flex-wrap: wrap;
}
.movie {
width: 300px;
border-radius: 4px;
box-shadow: 0 4px 5px rgba(0, 0, 0, 0.3);
background-color: #373b69;
margin: 25px;
}
.movie-info {
color: #eee;
display: flex;
justify-content: space-between;
padding: 10px;
letter-spacing: 1px;
align-items: center;
}
.movie img {
width: 100%;
border-bottom: 1px solid white;
height: 450px;
}
.movie-info h3 {
font-weight: 300;
margin: 0;
}
.movie-info span {
font-weight: 400;
border-radius: 3px;
background-color: #22254b;
padding: 3px 7px;
}
.movie .kupi {
color: #eee;
display: flex;
justify-content: space-between;
padding: 10px;
padding-bottom: 15px;
letter-spacing: 1px;
align-items: center;
}
.movie .kupi button {
padding: 2px 8px;
font-size: 14px;
font-weight: 500;
}
.movie .kupi span {
font-size: 18px;
font-weight: 500;
}
/* ----------------------------------- SHOOPING CART ------------------------------------------------ */
.shooping-cart {
border-top: 2px solid rgb(214, 214, 214);
width: 1000px;
height: 500px;
margin-left: 25px;
}
h2 {
color: whitesmoke;
text-transform: uppercase;
font-size: 20px;
font-weight: 300;
margin-bottom: 20px;
margin-left: 25px;
}
.shooping-cart .single-item {
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
padding: 20px;
border-bottom: 2px dotted grey;
}
.shooping-cart .single-item span {
background-color: rgb(255, 255, 255);
margin-left: 20px;
border-radius: 50%;
color: black;
}
.smallPic {
height: 70px;
width: 70px;
border: 1px solid grey;
}
.shooping-cart .single-item .opis {
align-items: center;
display: flex;
flex-direction: column;
color: white;
font-family: inherit;
}
.shooping-cart .single-item .opis h2 {
font-weight: 300;
margin-bottom: 5px;
}
.shooping-cart .single-item .opis h3 {
font-size: 14px;
font-weight: bold;
color: antiquewhite;
text-transform: uppercase;
}
.shooping-cart .single-item .kolicina input {
width: 30px;
text-align: center;
}
.shooping-cart .single-item .kolicina button {
padding: 2px 6px;
background-color: whitesmoke;
border: 0;
}
.single-total {
color: white;
margin-right: 20px;
}
/* ----------------------------------- SHOOPING CART TOTAL ALL ------------------------------------------------ */
.totalKosara {
float: right;
display: flex;
flex-direction: column;
width: 350px;
height: 160px;
margin-top: 15px;
}
.potvrdi {
display: flex;
width: 100%;
margin: 20px 0;
justify-content: space-between;
text-align: center;
}
.potvrdi .sub,
.price {
color: #eee;
font-weight: bold;
padding: 5px;
}
.text {
color: white;
font-size: 14px;
text-align: center;
}
.blue {
width: 100%;
align-items: center;
display: flex;
justify-content: center;
margin-top: 30px;
}
.blue button {
width: 100%;
border-radius: 2px;
border: 0;
padding: 10px;
background-color: #0b1050;
color: #eee;
font-family: inherit;
border: 1px solid grey;
}
scriptJS
const options = {
method: "GET",
headers: {
"X-RapidAPI-Key": "cd782e9b03mshbd50bac036f1802p16179djsn48c38f33f263",
"X-RapidAPI-Host": "online-movie-database.p.rapidapi.com",
},
};
const main = document.querySelector(`.prozor`);
const shoopingCart = document.querySelector(`.shooping-cart`);
const checkoutBtn = document.querySelector(`.checkoutBtn`);
fetch(
"https://online-movie-database.p.rapidapi.com/auto-complete?q=hacker",
options
)
.then((response) => response.json())
.then((data) => {
const list = data.d;
list.map((item) => {
const name = item.l;
const rank = item.rank;
const price = Math.floor(rank / 100);
const poster = item.i.imageUrl;
const movie = ` <div class="movie">
<img src=${poster} alt="${name}" />
<div class="movie-info">
<h3>${name}</h3>
<span>#${rank}</span>
</div>
<div class="kupi">
<button class="addToBag">Kupi film</button>
<span>${price} HRK</span>
</div>
</div>`;
main.innerHTML += movie;
//---------------------------------- add to basket --------------------------//
const button = document.querySelectorAll(`.addToBag`);
button.forEach((button) => {
button.addEventListener(`click`, function (e) {
const clicked = e.target;
const kupi = clicked.closest(`.kupi`);
const cijena2 = kupi.querySelector(`span`).innerText;
const cijena = cijena2.split(` `)[0];
const parent = kupi.closest(`.movie`);
const imeFilma = parent.querySelector(`.movie-info h3`).innerText;
const imgSrc = parent.querySelector(`img`).src;
const singleItem = `
<div class="single-item">
<span class="material-symbols-outlined deleteItem"> close </span>
<img src=${imgSrc} alt="aaa" class="smallPic" />
<div class="opis">
<h2>${imeFilma}</h2>
</div>
<div class="kolicina">
<button class="plus">+</button>
<input type="text" value="1" max="3" min="1" class="input"/>
<button class="minus">-</button>
</div>
<div class="single-total" data-value="${cijena}">${cijena} KN</div>
</div>
`;
shoopingCart.innerHTML += singleItem;
const basketTotal = `
<div class="totalKosara vidljivo">
<div class="potvrdi">
<p class="sub">Subtotal</p>
<p class="price">675 KN</p>
</div>
<div class="text">
<p>Shipping, taxes and discounts calculated at checkout.</p>
</div>
<div class="blue"><button>Checkout</button></div>
</div>
`;
const removeElement = function () {
const nodes = document.querySelectorAll(`.single-item`);
let lastNode = nodes[nodes.length - 1];
console.log(lastNode);
};
removeElement();
//OBRISI ITEM
const deleteItem = document.querySelectorAll(`.deleteItem`);
deleteItem.forEach((btn) => {
btn.addEventListener(`click`, function (e) {
const mainEl = e.target.closest(`.single-item`);
mainEl.parentNode.removeChild(mainEl);
button.disabled = false;
});
});
//add more movies btn
const plusBtn = document.querySelectorAll(`.plus`);
const minusBtn = document.querySelectorAll(`.minus`);
plusBtn.forEach((btn) => {
btn.addEventListener(`click`, function (e) {
let plus = e.target;
let parent = plus.closest(`.kolicina`);
let input = parent.querySelector(`.input`);
let singleEl = parent.closest(`.single-item`);
let singleTotal = singleEl.querySelector(`.single-total`);
input.value++;
if (input.value > 3) input.value = 3;
singleTotal.innerText = `${
singleTotal.dataset.value * input.value
} KN`;
});
});
minusBtn.forEach((btn) => {
btn.addEventListener(`click`, function (e) {
let plus = e.target;
let parent = plus.closest(`.kolicina`);
let input = parent.querySelector(`.input`);
let singleEl = parent.closest(`.single-item`);
let singleTotal = singleEl.querySelector(`.single-total`);
input.value--;
console.log(input.innerText);
if (input.value < 1) input.value = 1;
singleTotal.innerText = `${
singleTotal.dataset.value * input.value
} KN`;
});
});
});
});
});
})
.catch(
(err) => console.error(err));
I couldn't understand clearly what you are trying to say. But as far as considered to append a child to parent div you can use
parentDiv.appendChild(childElement);
Appreciate it if you can make the question more understable.
I am fairly new to javascript, and am working on a note-taking app to practice some things I have learned so far. It all works fine, however, when I click on the Read More button to view overflow text of the note, it displays the text from the most recent note, as opposed to the note I click Read More on. I want the entire text of a particular note to be displayed when its corresponding Read More button is pressed. Am I overthinking this? I think some kind of implementation of for...of, or for loops may help me achieve this outcome. This is a link to my codepen: https://codepen.io/oliverc96/pen/xxdZYrr
const addNote = document.querySelector('.add-note');
const newNote = document.querySelector('#new-note');
const noteFeed = document.querySelector('#note-feed');
let modalBg = document.createElement('div');
let modalWindow = document.createElement('div');
let exitSymbol = document.createElement('i');
let modalText = document.createElement('p');
function expandNote() {
modalWindow.classList.add('enterAnimation');
modalBg.style.visibility = 'visible';
exitSymbol.addEventListener('click', () => {
modalBg.style.visibility = 'hidden';
modalWindow.classList.remove('enterAnimation');
})
}
function createNote() {
const noteContainer = document.createElement('div');
noteContainer.classList.add('containerStyle');
let noteHeader = document.createElement('h1');
const noteNum = noteFeed.childElementCount;
noteHeader.innerText = `Note #${noteNum + 1}`;
noteHeader.classList.add('headerStyle');
noteContainer.append(noteHeader);
let noteText = document.createElement('p');
noteText.innerText = `${newNote.value}`;
noteText.classList.add('paraStyle');
noteContainer.append(noteText);
let readMore = document.createElement('button');
readMore.innerText = 'Read More';
readMore.classList.add('btnStyle');
noteContainer.append(readMore);
noteFeed.append(noteContainer);
readMore.addEventListener('click', expandNote);
modalBg.classList.add('modal-bg');
modalWindow.classList.add('modal-window');
exitSymbol.className = 'far fa-times-circle';
exitSymbol.classList.add('exitSymbol');
modalWindow.append(exitSymbol);
modalText.classList.add('fullTextStyle');
modalText.innerText = `${noteText.innerText}`;
modalWindow.append(modalText);
modalBg.append(modalWindow);
noteContainer.append(modalBg);
newNote.value = '';
}
addNote.addEventListener('click', createNote);
newNote.addEventListener('keyup', function(e) {
if (e.keyCode === 13) {
e.preventDefault();
createNote();
}
})
Actually your modalText will always store the latest value according to your code. You can follow the following steps to solve this.
Attach an data-attribute to that noteText.
When click on read more pass the id of that specific note.
Now just show the innerText of that selected item. You can use querySelector to get the element using data-attribute.
You can check my implementation.
console.clear();
const addNote = document.querySelector('.add-note');
const newNote = document.querySelector('#new-note');
const noteFeed = document.querySelector('#note-feed');
let modalBg = document.createElement('div');
let modalWindow = document.createElement('div');
let exitSymbol = document.createElement('i');
let modalText = document.createElement('p');
function expandNote(noteContainer, noteNum) {
return function () {
modalWindow.classList.add('enterAnimation');
modalBg.style.visibility = 'visible';
exitSymbol.addEventListener('click', () => {
modalBg.style.visibility = 'hidden';
modalWindow.classList.remove('enterAnimation');
})
const data = document.querySelector(`[data-id='${noteNum}']`).innerText;
showMoreModal(noteContainer, data);
}
}
function showMoreModal(noteContainer, data) {
modalBg.classList.add('modal-bg');
modalWindow.classList.add('modal-window');
exitSymbol.className = 'far fa-times-circle';
exitSymbol.classList.add('exitSymbol');
modalWindow.append(exitSymbol);
modalText.classList.add('fullTextStyle');
modalText.innerText = `${data}`;
modalWindow.append(modalText);
modalBg.append(modalWindow);
noteContainer.append(modalBg);
}
function createNote() {
const noteContainer = document.createElement('div');
noteContainer.classList.add('containerStyle');
let noteHeader = document.createElement('h1');
const noteNum = noteFeed.childElementCount;
noteHeader.innerText = `Note #${noteNum + 1}`;
noteHeader.classList.add('headerStyle');
noteContainer.append(noteHeader);
let noteText = document.createElement('p');
noteText.innerText = `${newNote.value}`;
noteText.classList.add('paraStyle');
noteText.setAttribute('data-id', noteNum);
noteContainer.append(noteText);
let readMore = document.createElement('button');
readMore.innerText = 'Read More';
readMore.classList.add('btnStyle');
noteContainer.append(readMore);
noteFeed.append(noteContainer);
readMore.addEventListener('click', expandNote(noteContainer, noteNum));
newNote.value = '';
}
addNote.addEventListener('click', createNote);
newNote.addEventListener('keyup', function(e) {
if (e.keyCode === 13) {
e.preventDefault();
createNote();
}
})
* {
padding: 0;
margin: 0;
box-sizing: border-box;
font-family: 'Montserrat', sans-serif;
}
#wrapper {
width: 1600px;
height: 100vh;
margin: auto;
text-align: center;
}
h1 {
font-size: 100px;
margin-top: 20px;
font-weight: 500;
}
h2 {
font-size: 50px;
font-weight: 400;
margin-top: 10px;
}
#add-new-note {
color: rgb(0, 153, 153);
}
textarea {
width: 1500px;
margin-top: 30px;
height: 60px;
border-radius: 6px;
padding: 20px;
font-size: 18px;
}
textarea:focus {
outline-color: black;
}
.add-note {
font-size: 20px;
width: 180px;
height: 50px;
border-radius: 6px;
margin-top: 30px;
background-color: rgb(0, 153, 153);
color: white;
border-style: solid;
border-color: rgb(0, 102, 102);
}
.add-note:hover {
background-color: rgb(0, 128, 128);
cursor: pointer;
}
#note-feed {
background-color: rgb(0, 153, 153);
height: 500px;
margin-top: 25px;
width: 1500px;
border-radius: 6px;
display: flex;
overflow: scroll;
flex-wrap: wrap;
padding: 20px 10px;
margin-left: 50px;
}
.containerStyle {
display: flex;
flex-direction: column;
justify-content: space-around;
background-color: rgb(169, 169, 214);
height: 48%;
width: 31%;
margin-right: 11px;
margin-left: 20px;
border-radius: 6px;
margin-bottom: 20px;
overflow: hidden;
padding: 0 28px;
padding-bottom: 15px;
text-align: left;
}
.headerStyle {
font-size: 30px;
}
.paraStyle {
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
font-size: 18px;
text-overflow: ellipsis;
overflow: hidden;
}
.btnStyle {
font-size: 20px;
width: 150px;
height: 40px;
border-radius: 6px;
background-color: rgb(255, 128, 128);
color: white;
border-style: solid;
border-color: rgb(255, 77, 77);
align-self: left;
}
.btnStyle:hover {
background-color: rgb(255, 102, 102);
cursor: pointer;
}
.modal-bg {
z-index: 1;
position: fixed;
width: 100%;
height: 100%;
top: 0;
left: 0;
background: rgba(0,0,0,0.5);
color: white;
display: flex;
justify-content: center;
align-items: center;
visibility: hidden;
overflow: scroll;
}
.modal-window {
border-radius: 6px;
background: white;
width: 70%;
min-height: 30%;
max-height: 70%;
overflow: scroll;
display: flex;
justify-content: flex-start;
align-items: flex-start;
}
.enterAnimation {
animation-name: fadeInDown;
animation-duration: 1s;
}
#keyframes fadeInDown {
0% {
opacity: 0;
transform: translateY(-200px);
}
100% {
opacity: 1;
}
}
.exitSymbol {
color: rgb(0, 128, 128);
font-size: 30px;
margin: 20px 20px;
}
.exitSymbol:hover {
cursor: pointer;
opacity: 0.8;
}
.fullTextStyle {
color: black;
width: 90%;
height: 80%;
text-align: left;
margin-top: 60px;
margin-bottom: 30px;
font-size: 18px;
}
<html>
<head>
<title> Note Taker </title>
<link type="text/css" href="notes.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght#100;200;300;400;500;600;700&display=swap" rel="stylesheet">
</head>
<body>
<div id="wrapper">
<h1> Note Taker </h1>
<h2 id="add-new-note"> Add A New Note: </h2>
<textarea id="new-note" name="note-box" placeholder="Write your note here"></textarea>
<button class="add-note"> Add Note </button>
<div id="note-feed">
</div>
</div>
<script src="notes.js"></script>
<script src="https://kit.fontawesome.com/6fc6f370ca.js" crossorigin="anonymous"></script>
</body>
</html>
I found a nice filterable select dropdown on Codepen, copied the code, and tried to get it working on my computer.
While the layout looks fine, filtering does not work locally.
Unfortunately, I have absolutely no idea why. Any help is appreciated.
Working original Codepen:
https://codepen.io/marijoha/pen/zKjvEw
My (non working) HTML file live online:
http://select-dropdown.bitballoon.com/
Download my HTML file:
https://send.firefox.com/download/bd917213cd/#mwjZbZTfXNNv6I8FTW5TLQ
My HTML files's code:
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-ms-flex-direction: column;
flex-direction: column;
width: 100%;
height: 100vh;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
-webkit-box-pack: start;
-ms-flex-pack: start;
justify-content: flex-start;
font-family: 'Ek Mukta';
text-transform: uppercase;
font-weight: 600;
letter-spacing: 4px;
background: #1D1F20;
}
h1 {
margin-top: 10vh;
font-size: 2.5rem;
max-width: 500px;
letter-spacing: 3px;
text-align: center;
line-height: 1.5;
font-family: 'Open Sans';
text-transform: capitalize;
font-weight: 800;
color: white;
}
h1 span {
color: #FF908B;
}
form {
position: relative;
width: 18rem;
margin-top: 8vh;
}
.chosen-value,
.value-list {
position: absolute;
top: 0;
left: 0;
width: 100%;
}
.chosen-value {
font-family: 'Ek Mukta';
text-transform: uppercase;
font-weight: 600;
letter-spacing: 4px;
height: 4rem;
font-size: 1.1rem;
padding: 1rem;
background-color: #FAFCFD;
border: 3px solid transparent;
-webkit-transition: .3s ease-in-out;
transition: .3s ease-in-out;
}
.chosen-value::-webkit-input-placeholder {
color: #333;
}
.chosen-value:hover {
background-color: #FF908B;
cursor: pointer;
}
.chosen-value:hover::-webkit-input-placeholder {
color: #333;
}
.chosen-value:focus, .chosen-value.open {
box-shadow: 0px 5px 8px 0px rgba(0, 0, 0, 0.2);
outline: 0;
background-color: #FF908B;
color: #000;
}
.chosen-value:focus::-webkit-input-placeholder, .chosen-value.open::-webkit-input-placeholder {
color: #000;
}
.value-list {
list-style: none;
margin-top: 4rem;
box-shadow: 0px 5px 8px 0px rgba(0, 0, 0, 0.2);
overflow: hidden;
max-height: 0;
-webkit-transition: .3s ease-in-out;
transition: .3s ease-in-out;
}
.value-list.open {
max-height: 320px;
overflow: auto;
}
.value-list li {
position: relative;
height: 4rem;
background-color: #FAFCFD;
padding: 1rem;
font-size: 1.1rem;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
cursor: pointer;
-webkit-transition: background-color .3s;
transition: background-color .3s;
opacity: 1;
}
.value-list li:hover {
background-color: #FF908B;
}
.value-list li.closed {
max-height: 0;
overflow: hidden;
padding: 0;
opacity: 0;
}
</style>
<link href="https://fonts.googleapis.com/css?family=Ek+Mukta:300,400,600|Open+Sans:400,800" rel="stylesheet">
<h1><span>Styled</span> and <span>filterable</span> select dropdown</h1>
<form>
<input class="chosen-value" type="text" value="" placeholder="Type to filter">
<ul class="value-list">
<li>Alabama</li>
<li>Alaska</li>
<li>Arizona</li>
<li>Arkansas</li>
<li>California</li>
<li>Colorado</li>
<li>Connecticut</li>
<li>Delaware</li>
<li>Florida</li>
<li>Georgia</li>
<li>Hawaii</li>
<li>Idaho</li>
<li>Illinois</li>
<li>Indiana</li>
<li>Iowa</li>
<li>Kansas</li>
<li>Kentucky</li>
<li>Louisiana</li>
<li>Maine</li>
<li>Maryland</li>
<li>Massachusetts</li>
<li>Michigan</li>
<li>Minnesota</li>
<li>Mississippi</li>
<li>Missouri</li>
<li>Montana</li>
<li>Nebraska</li>
<li>Nevada</li>
<li>New Hampshire</li>
<li>New Jersey</li>
<li>New Mexico</li>
<li>New York</li>
<li>North Carolina</li>
<li>North Dakota</li>
<li>Ohio</li>
<li>Oklahoma</li>
<li>Oregon</li>
<li>Pennsylvania</li>
<li>Rhode Island</li>
<li>South Carolina</li>
<li>South Dakota</li>
<li>Tennessee</li>
<li>Texas</li>
<li>Utah</li>
<li>Vermont</li>
<li>Virginia</li>
<li>Washington</li>
<li>West Virginia</li>
<li>Wisconsin</li>
<li>Wyoming</li>
</ul>
</form>
<script>
'use strict';
var inputField = document.querySelector('.chosen-value');
var dropdown = document.querySelector('.value-list');
var dropdownArray = [].concat(document.querySelectorAll('li'));
var dropdownItems = dropdownArray[0];
dropdown.classList.add('open');
inputField.focus(); // Demo purposes only
var valueArray = [];
dropdownItems.forEach(function (item) {
valueArray.push(item.textContent);
});
var closeDropdown = function closeDropdown() {
dropdown.classList.remove('open');
};
inputField.addEventListener('input', function () {
dropdown.classList.add('open');
var inputValue = inputField.value.toLowerCase();
var valueSubstring = undefined;
if (inputValue.length > 0) {
for (var j = 0; j < valueArray.length; j++) {if (window.CP.shouldStopExecution(1)){break;}
if (!(inputValue.substring(0, inputValue.length) === valueArray[j].substring(0, inputValue.length).toLowerCase())) {
dropdownItems[j].classList.add('closed');
} else {
dropdownItems[j].classList.remove('closed');
}
}
window.CP.exitedLoop(1);
} else {
for (var i = 0; i < dropdownItems.length; i++) {if (window.CP.shouldStopExecution(2)){break;}
dropdownItems[i].classList.remove('closed');
}
window.CP.exitedLoop(2);
}
});
dropdownItems.forEach(function (item) {
item.addEventListener('click', function (evt) {
inputField.value = item.textContent;
dropdownItems.forEach(function (dropdown) {
dropdown.classList.add('closed');
});
});
});
inputField.addEventListener('focus', function () {
inputField.placeholder = 'Type to filter';
dropdown.classList.add('open');
dropdownItems.forEach(function (dropdown) {
dropdown.classList.remove('closed');
});
});
inputField.addEventListener('blur', function () {
inputField.placeholder = 'Select state';
dropdown.classList.remove('open');
});
document.addEventListener('click', function (evt) {
var isDropdown = dropdown.contains(evt.target);
var isInput = inputField.contains(evt.target);
if (!isDropdown && !isInput) {
dropdown.classList.remove('open');
}
});
</script>
</html>
just deleting all the if (window.CP.shouldStopExecution(*some number*)){break;} and
window.CP.exitedLoop(*some number*); fixes your issue.
window.CP is an something CodePen made to exit infinite loops.
Codepen had a post about this explaining the function as follows:
"The logic to detect a hanging for loop is simple. Possibly too simple. That number passed to the shouldStopExecution function is the loop identifier.
shouldStopExecution keeps track of when a function was first called. If the same loop is called for more than 75ms we break out of the loop."
src: codepen.io/quezo/post/stopping-infinite-loops
This question already has an answer here:
Flex items create space between them when they wrap [duplicate]
(1 answer)
Closed 6 years ago.
I am making a simple pen on CodePen, where you can add and remove blocks from a box. It's really simple, and it is working fully except for one thing. I am using flex-wrap to make the overflow go into separate columns but it has an unwanted space in the middle of the rows. I am awarer that this is the default of flex-wrap, but I am wondering if there is a way to get rid of the space between the rows. My pen is here: http://codepen.io/TheAndersMan/pen/KggVOj
Also, I am using SCSS
Here is my HTML:
<div class="buttonWrap">
<button>Add</button>
<button class="two">Subtract</button>
</div>
<div class="box"></div>
My CSS:
#import 'https://fonts.googleapis.com/css?family=Roboto:300';
body {
margin: 0;
display: flex;
align-items: center;
}
.buttonWrap {
margin-top: 37.5vh;
margin-left: 7.5vw;
&:nth-child(1) {
margin-bottom: 5vh;
}
button {
cursor: pointer;
outline: none;
background: #3f51b5;
border: none;
color: white;
width: 10vw;
height: 10vh;
font-size: 2em;
font-family: roboto;
display: block;
// margin-top: 5vh;
}
.two {
margin-top: 5vh;
}
}
.box {
position: absolute;
height: 50vh;
width: 50vw;
left: 25vw;
top: 25vh;
background: #ff5252;
display: flex;
flex-wrap: wrap;
}
.newDiv {
background: #3f51b5;
width: 5vw;
height: 5vh;
z-index: 10;
}
#media (max-width: 1350px) {
.buttonWrap {
button {
font-size: 1em;
}
}
}
And my JS:
var add = document.querySelector("button");
var subtract = document.querySelector(".two");
var box = document.querySelector(".box");
add.addEventListener("click", function() {
var newDiv = document.createElement("div");
var newContent = document.createTextNode("");
newDiv.classList.add("newDiv")
newDiv.appendChild(newContent);
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
box.appendChild(newDiv);
})
subtract.addEventListener("click", function() {
document.querySelector(".newDiv:last-of-type").remove();
})
So is there any way I can fix this?
Add this to your .box:
align-content: flex-start;
var add = document.querySelector("button");
var subtract = document.querySelector(".two");
var box = document.querySelector(".box");
add.addEventListener("click", function() {
var newDiv = document.createElement("div");
var newContent = document.createTextNode("");
newDiv.classList.add("newDiv")
newDiv.appendChild(newContent);
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
box.appendChild(newDiv);
})
subtract.addEventListener("click", function() {
document.querySelector(".newDiv:last-of-type").remove();
})
Roboto:300';
body {
margin: 0;
display: flex;
align-items: center;
}
.buttonWrap {
margin-top: 37.5vh;
margin-left: 7.5vw;
&:nth-child(1) {
margin-bottom: 5vh;
}
button {
cursor: pointer;
outline: none;
background: #3f51b5;
border: none;
color: white;
width: 10vw;
height: 10vh;
font-size: 2em;
font-family: roboto;
display: block;
// margin-top: 5vh;
}
.two {
margin-top: 5vh;
}
}
.box {
position: absolute;
height: 50vh;
width: 50vw;
left: 25vw;
top: 25vh;
background: #ff5252;
display: flex;
flex-wrap: wrap;
align-content: flex-start; /* <-- this here */
}
.newDiv {
background: #3f51b5;
width: 5vw;
height: 5vh;
z-index: 10;
}
#media (max-width: 1350px) {
.buttonWrap {
button {
font-size: 1em;
}
}
}
<div class="buttonWrap">
<button>Add</button>
<button class="two">Subtract</button>
</div>
<div class="box"></div>
Further reading: https://developer.mozilla.org/en-US/docs/Web/CSS/align-content