Serve text instead of images - Trivia javascript game - javascript

I have a working code of a 10 questions' trivia game with a timer (html, javascript, css), that serves images from a folder, and has 4 options for answers.
I want to serve text questions instead of images. Can you assist?
I have manipulated severely the css and html code (and a little the js) to make it cleaner and simpler, using ideas from codepen and the internet. However, my javascript skills are very limited.
(function() {
const playButton = document.querySelector("#play");
const letsstartButton = document.querySelector("#lets-start");
const playagainButton = document.querySelector("#play-again");
const howToPlayButton = document.querySelector("#how-to-play-button");
const closeHowToButton = document.querySelector("#close-how-to");
const howToPlayScreen = document.querySelector(".how-to-play-screen");
const mainScreen = document.querySelector(".main-screen");
const triviaScreen = document.querySelector(".trivia-screen");
const resultScreen = document.querySelector(".result-screen");
playButton.addEventListener("click", startTrivia);
letsstartButton.addEventListener("click", startTrivia);
playagainButton.addEventListener("click", startTrivia);
howToPlayButton.addEventListener("click", function() {
howToPlayScreen.classList.remove("hidden");
mainScreen.classList.add("hidden");
});
closeHowToButton.addEventListener("click", function() {
howToPlayScreen.classList.add("hidden");
mainScreen.classList.remove("hidden");
});
const questionLength = 10;
let questionIndex = 0;
let score = 0;
let questions = [];
let timer = null;
function startTrivia() {
//show spinner
questionIndex = 0;
questions = [];
score = 0;
window.setTimeout(function() {
//get questions from server
mainScreen.classList.add("hidden");
howToPlayScreen.classList.add("hidden");
resultScreen.classList.add("hidden");
triviaScreen.classList.remove("hidden");
questions = [{
answers: ["Roma", "Athens", "London", "Japan"],
correct: "Roma",
image: "001"
},
{
answers: ["Roma1", "Athens1", "London1", "Japan1"],
correct: "Athens1",
image: "002"
},
{
answers: ["Roma2", "Athens2", "London2", "Japan2"],
correct: "London2",
image: "003"
},
{
answers: ["Roma3", "Athens3", "London3", "Japan3"],
correct: "London3",
image: "004"
},
{
answers: ["Roma4", "Athens4", "London4", "Japan4"],
correct: "Athens4",
image: "005"
},
{
answers: ["Roma5", "Athens5", "London5", "Japan5"],
correct: "Athens5",
image: "006"
},
{
answers: ["Roma6", "Athens6", "London6", "Japan6"],
correct: "Roma6",
image: "007"
},
{
answers: ["Roma7", "Athens7", "London7", "Japan7"],
correct: "Japan7",
image: "008"
},
{
answers: ["Roma8", "Athens8", "London8", "Japan8"],
correct: "London8",
image: "009"
},
{
answers: ["Roma9", "Athens9", "London9", "Japan9"],
correct: "Japan9",
image: "010"
}
];
const questionCount = document.getElementById("question-count");
questionCount.innerHTML = questionLength.toString();
displayNextQuestion();
}, 50);
}
const isTriviaCompleted = function() {
return questionLength === questionIndex;
};
function displayNextQuestion() {
const answersContainer = document.getElementById("answers-container");
const answerButtons = answersContainer.querySelectorAll(".default-button");
answerButtons.forEach(function(element) {
element.disabled = false;
element.classList.remove("correct");
element.classList.remove("wrong");
});
if (isTriviaCompleted()) {
showScores();
} else {
startProgressbar();
timer = window.setTimeout(function() {
guess(null);
}, 10000);
setQuizText("This is from");
const imageElement = document.getElementById("question-placement");
imageElement.src = `./assets/images/${questions[questionIndex].image}.png`;
const choices = questions[questionIndex].answers;
for (let i = 0; i < choices.length; i++) {
const element = document.getElementById(`answer${i}`);
element.innerHTML = choices[i];
element.addEventListener("click", handleAnswerClick);
}
showProgress();
}
}
function handleAnswerClick(e) {
const el = e.currentTarget;
const answer = el.innerHTML;
el.removeEventListener("click", handleAnswerClick);
guess(answer);
}
function showProgress() {
const questionIndexElement = document.getElementById("question-index");
const index = questionIndex + 1;
questionIndexElement.innerHTML = index.toString();
}
function guess(answer) {
clearTimeout(timer);
const answersContainer = document.getElementById("answers-container");
const answerButtons = answersContainer.querySelectorAll(".default-button");
answerButtons.forEach((element) => {
element.disabled = true;
if (element.innerHTML === questions[questionIndex].correct) {
element.classList.add("correct");
}
});
stopProgressbar();
if (questions[questionIndex].correct === answer) { // correct answer
score++;
setQuizText("Fantastic … Correct!");
} else if (answer) { // incorrect answer
setQuizText("Nice try … You were close.");
answerButtons.forEach((element) => {
if (element.innerHTML === answer) {
element.classList.add("wrong");
}
});
} else {
setQuizText("Your time is out! Oh no!");
}
questionIndex++;
window.setTimeout(function() {
displayNextQuestion();
}, 2500);
}
function setQuizText(text) {
const el = document.getElementById("trivia-text");
el.innerHTML = text;
}
function showScores() {
const scoreElement = document.getElementById("score");
const scoreTotalElement = document.getElementById("score-total");
const scoreNameElement = document.getElementById("score-name");
scoreElement.innerHTML = score.toString();
scoreTotalElement.innerHTML = questionLength.toString();
if (score < 4) {
scoreNameElement.innerHTML = "Newbie";
} else if (score < 7) {
scoreNameElement.innerHTML = "Rookie";
} else if (score < 10) {
scoreNameElement.innerHTML = "Expert";
} else {
scoreNameElement.innerHTML = "Grandmaster";
}
triviaScreen.classList.add("hidden");
resultScreen.classList.remove("hidden");
}
function startProgressbar() {
// select div turn into progressbar
const progressbar = document.getElementById("progress-bar");
progressbar.innerHTML = "";
// create div changes width show progress
const progressbarInner = document.createElement("span");
// Append progressbar to main progressbardiv
progressbar.appendChild(progressbarInner);
// When all set start animation
progressbarInner.style.animationPlayState = "running";
}
function stopProgressbar() {
const progressbar = document.getElementById("progress-bar");
const progressbarInner = progressbar.querySelector("span");
progressbarInner.style.animationPlayState = "paused";
}
}());
*,
*:after,
*:before {
box-sizing: border-box;
}
body {
margin: 0;
font-family: 'Verdana', cursive;
text-transform: uppercase;
color: #ccc;
letter-spacing: 2px;
}
.container {
background: #999999;
}
.wrapper {
max-width: 800px;
margin: auto;
}
.screen-section {
display: flex;
flex-direction: column;
align-items: center;
min-height: 100vh;
padding: 20px 20px 70px;
position: relative;
}
.hidden {
display: none;
}
.trivia-screen-step {
color: #ccc;
}
.trivia-image-wrapper {
max-width: 100%;
margin: 50px auto;
position: relative;
}
.trivia-image {
max-width: 100%;
width: 300px;
position: relative;
z-index: 1;
}
.trivia-timer {
width: 550px;
max-width: 100%;
height: 20px;
border-radius: 3em;
margin-bottom: 50px;
padding: 5px 6px;
}
.trivia-timer span {
display: inline-block;
background: linear-gradient(90deg, #fff, #06c);
height: 10px;
vertical-align: top;
border-radius: 3em;
animation: progressbar-countdown;
animation-duration: 10s;
animation-iteration-count: 1;
animation-fill-mode: forwards;
animation-play-state: paused;
animation-timing-function: linear;
}
#keyframes progressbar-countdown {
0% {
width: 100%;
}
100% {
width: 0%;
}
}
.trivia-question {
margin-bottom: 50px;
}
.how-to-play-screen .default-button {
margin-bottom: 60px;
margin-top: 30px;
}
.button-container {
display: flex;
flex-wrap: wrap;
margin-bottom: 50px;
width: 600px;
max-width: 100%;
}
.button-outer {
flex-basis: 100%;
text-align: center;
margin-bottom: 20px;
max-width: 100%;
}
.default-button {
background: #333333;
border-radius: 3em;
font-family: 'Verdana', cursive;
font-size: 18px;
color: #fff;
letter-spacing: 2.45px;
padding: 10px 8px;
text-transform: uppercase;
transition: background .2s;
outline: none;
width: 250px;
cursor: pointer;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 100%;
}
.default-button:hover {
background: #222;
}
.default-button[disabled] {
background: transparent;
color: #222;
cursor: default;
}
.default-button[disabled]:hover {
background: transparent;
}
.default-button.correct {
cursor: default;
background: #2bb24a;
color: #fff;
}
.default-button.correct:hover {
background: #2bb24a;
color: #fff;
}
.default-button.wrong {
cursor: default;
background: #F6484C;
color: #fff;
}
.default-button.wrong:hover {
background: #F6484C;
color: #fff;
}
.title {
font-size: 32px;
margin-top: 100px;
}
.text {
line-height: 24px;
font-size: 16px;
font-family: 'Verdana', sans-serif;
text-align: center;
color: #ffffff;
text-transform: none;
}
.trivia-logo {
position: absolute;
bottom: 20px;
}
.trivia-corner-logo {
position: absolute;
left: 0;
top: 15px;
width: 100px;
}
.close-button {
position: absolute;
top: 50px;
right: 0;
background: transparent;
border: none;
color: #fff;
font-family: 'Verdana', cursive;
font-size: 34px;
outline: none;
text-transform: none;
cursor: pointer;
transition: color .2s;
}
.close-button:hover {
color: #eee;
}
.score-name {
margin: 0 0 28px;
font-size: 46px;
}
.score {
font-size: 18px;
margin-bottom: 10px;
}
.description {
text-align: center;
font-family: Verdana, sans-serif;
font-size: 16px;
color: #fff;
text-transform: none;
line-height: 24px;
display: inline-block;
margin-bottom: 30px;
}
#media screen and (min-width: 700px) {
.screen-section {
padding: 50px;
}
.button-outer {
flex-basis: 50%;
}
}
<div class="container">
<div class="wrapper">
<div class="screen-section main-screen">
<div class="trivia-image-wrapper">
<img alt="LOGO" src="/assets/Game-Logo.png" class="trivia-image">
</div>
<h1>Trivia</h1>
<div class="button-container">
<div class="button-outer">
<button class="default-button" id="play" type="button">Play</button>
</div>
<div class="button-outer">
<button class="default-button" id="how-to-play-button" type="button">How to play?</button>
</div>
</div>
<div class="trivia-logo">
<img alt="logo" src="/assets/-Logo.png">
</div>
</div>
<div class="screen-section hidden how-to-play-screen">
<img alt="LOGO" src="/assets/Game-Logo.png" class="trivia-corner-logo">
<button class="close-button" id="close-how-to" type="button">x</button>
<h2 class="title">How to Play</h2>
<p>Answer questions to score points.</p>
<button class="default-button" id="lets-start" type="button">Ok. Let's start</button>
<div class="trivia-logo">
<img alt="logo" src="/assets/-Logo.png">
</div>
</div>
<div class="screen-section hidden trivia-screen">
<div class="trivia-screen-step"><span id="question-index">1</span> out of <span id="question-count">10</span></div>
<div class="trivia-image-wrapper">
<img alt="image" src="IMAGE-URL" class="trivia-image" id="question-placement">
</div>
<div class="trivia-timer" id="progress-bar"></div>
<div class="trivia-question" id="trivia-text"></div>
<div class="button-container" id="answers-container">
<div class="button-outer">
<button class="default-button" id="answer0" type="button"></button>
</div>
<div class="button-outer">
<button class="default-button" id="answer1" type="button"></button>
</div>
<div class="button-outer">
<button class="default-button" id="answer2" type="button"></button>
</div>
<div class="button-outer">
<button class="default-button" id="answer3" type="button"></button>
</div>
</div>
<div class="trivia-logo">
<img alt="logo" src="/assets/-Logo.png">
</div>
</div>
<div class="screen-section hidden result-screen">
<div class="trivia-image-wrapper">
<img alt="Trivia LOGO" src="/assets/Game-Logo.png" class="trivia-image">
</div>
<p class="score"><span id="score">0</span> out of <span id="score-total">10</span></p>
<h1 class="score-name" id="score-name">Trivia</h1>
<span class="description">you will learn more.</span>
<button class="default-button" id="play-again" type="button">Play again</button>
<div class="trivia-logo">
<img alt=" logo" src="/assets/-Logo.png">
</div>
</div>
</div>
</div>

Just change the <img> tag for a <p> tag and replace the image filenames inside the variable questions for your question text. Then change these 2 lines:
const imageElement = document.getElementById("question-placement");
imageElement.src = `./assets/images/${questions[questionIndex].image}.png`;
for these 2 lines:
const textElement = document.getElementById("question-placement");
textElement.innerHTML = questions[questionIndex].text;
Everything is pretty straightforward.
(function() {
const playButton = document.querySelector("#play");
const letsstartButton = document.querySelector("#lets-start");
const playagainButton = document.querySelector("#play-again");
const howToPlayButton = document.querySelector("#how-to-play-button");
const closeHowToButton = document.querySelector("#close-how-to");
const howToPlayScreen = document.querySelector(".how-to-play-screen");
const mainScreen = document.querySelector(".main-screen");
const triviaScreen = document.querySelector(".trivia-screen");
const resultScreen = document.querySelector(".result-screen");
playButton.addEventListener("click", startTrivia);
letsstartButton.addEventListener("click", startTrivia);
playagainButton.addEventListener("click", startTrivia);
howToPlayButton.addEventListener("click", function() {
howToPlayScreen.classList.remove("hidden");
mainScreen.classList.add("hidden");
});
closeHowToButton.addEventListener("click", function() {
howToPlayScreen.classList.add("hidden");
mainScreen.classList.remove("hidden");
});
const questionLength = 10;
let questionIndex = 0;
let score = 0;
let questions = [];
let timer = null;
function startTrivia() {
//show spinner
questionIndex = 0;
questions = [];
score = 0;
window.setTimeout(function() {
//get questions from server
mainScreen.classList.add("hidden");
howToPlayScreen.classList.add("hidden");
resultScreen.classList.add("hidden");
triviaScreen.classList.remove("hidden");
questions = [{
answers: ["Roma", "Athens", "London", "Japan"],
correct: "Roma",
text: "YOUR TEXT HERE."
},
{
answers: ["Roma1", "Athens1", "London1", "Japan1"],
correct: "Athens1",
text: "YOUR TEXT HERE."
},
{
answers: ["Roma2", "Athens2", "London2", "Japan2"],
correct: "London2",
text: "YOUR TEXT HERE."
},
{
answers: ["Roma3", "Athens3", "London3", "Japan3"],
correct: "London3",
text: "YOUR TEXT HERE."
},
{
answers: ["Roma4", "Athens4", "London4", "Japan4"],
correct: "Athens4",
text: "YOUR TEXT HERE."
},
{
answers: ["Roma5", "Athens5", "London5", "Japan5"],
correct: "Athens5",
text: "YOUR TEXT HERE."
},
{
answers: ["Roma6", "Athens6", "London6", "Japan6"],
correct: "Roma6",
text: "YOUR TEXT HERE."
},
{
answers: ["Roma7", "Athens7", "London7", "Japan7"],
correct: "Japan7",
text: "YOUR TEXT HERE."
},
{
answers: ["Roma8", "Athens8", "London8", "Japan8"],
correct: "London8",
text: "YOUR TEXT HERE."
},
{
answers: ["Roma9", "Athens9", "London9", "Japan9"],
correct: "Japan9",
text: "YOUR TEXT HERE."
}
];
const questionCount = document.getElementById("question-count");
questionCount.innerHTML = questionLength.toString();
displayNextQuestion();
}, 50);
}
const isTriviaCompleted = function() {
return questionLength === questionIndex;
};
function displayNextQuestion() {
const answersContainer = document.getElementById("answers-container");
const answerButtons = answersContainer.querySelectorAll(".default-button");
answerButtons.forEach(function(element) {
element.disabled = false;
element.classList.remove("correct");
element.classList.remove("wrong");
});
if (isTriviaCompleted()) {
showScores();
} else {
startProgressbar();
timer = window.setTimeout(function() {
guess(null);
}, 10000);
setQuizText("This is from");
const textElement = document.getElementById("question-placement");
textElement.innerHTML = questions[questionIndex].text;
const choices = questions[questionIndex].answers;
for (let i = 0; i < choices.length; i++) {
const element = document.getElementById(`answer${i}`);
element.innerHTML = choices[i];
element.addEventListener("click", handleAnswerClick);
}
showProgress();
}
}
function handleAnswerClick(e) {
const el = e.currentTarget;
const answer = el.innerHTML;
el.removeEventListener("click", handleAnswerClick);
guess(answer);
}
function showProgress() {
const questionIndexElement = document.getElementById("question-index");
const index = questionIndex + 1;
questionIndexElement.innerHTML = index.toString();
}
function guess(answer) {
clearTimeout(timer);
const answersContainer = document.getElementById("answers-container");
const answerButtons = answersContainer.querySelectorAll(".default-button");
answerButtons.forEach((element) => {
element.disabled = true;
if (element.innerHTML === questions[questionIndex].correct) {
element.classList.add("correct");
}
});
stopProgressbar();
if (questions[questionIndex].correct === answer) { // correct answer
score++;
setQuizText("Fantastic … Correct!");
} else if (answer) { // incorrect answer
setQuizText("Nice try … You were close.");
answerButtons.forEach((element) => {
if (element.innerHTML === answer) {
element.classList.add("wrong");
}
});
} else {
setQuizText("Your time is out! Oh no!");
}
questionIndex++;
window.setTimeout(function() {
displayNextQuestion();
}, 2500);
}
function setQuizText(text) {
const el = document.getElementById("trivia-text");
el.innerHTML = text;
}
function showScores() {
const scoreElement = document.getElementById("score");
const scoreTotalElement = document.getElementById("score-total");
const scoreNameElement = document.getElementById("score-name");
scoreElement.innerHTML = score.toString();
scoreTotalElement.innerHTML = questionLength.toString();
if (score < 4) {
scoreNameElement.innerHTML = "Newbie";
} else if (score < 7) {
scoreNameElement.innerHTML = "Rookie";
} else if (score < 10) {
scoreNameElement.innerHTML = "Expert";
} else {
scoreNameElement.innerHTML = "Grandmaster";
}
triviaScreen.classList.add("hidden");
resultScreen.classList.remove("hidden");
}
function startProgressbar() {
// select div turn into progressbar
const progressbar = document.getElementById("progress-bar");
progressbar.innerHTML = "";
// create div changes width show progress
const progressbarInner = document.createElement("span");
// Append progressbar to main progressbardiv
progressbar.appendChild(progressbarInner);
// When all set start animation
progressbarInner.style.animationPlayState = "running";
}
function stopProgressbar() {
const progressbar = document.getElementById("progress-bar");
const progressbarInner = progressbar.querySelector("span");
progressbarInner.style.animationPlayState = "paused";
}
}());
*,
*:after,
*:before {
box-sizing: border-box;
}
body {
margin: 0;
font-family: 'Verdana', cursive;
text-transform: uppercase;
color: #ccc;
letter-spacing: 2px;
}
.container {
background: #999999;
}
.wrapper {
max-width: 800px;
margin: auto;
}
.screen-section {
display: flex;
flex-direction: column;
align-items: center;
min-height: 100vh;
padding: 20px 20px 70px;
position: relative;
}
.hidden {
display: none;
}
.trivia-screen-step {
color: #ccc;
}
.trivia-image-wrapper {
max-width: 100%;
margin: 50px auto;
position: relative;
}
.trivia-image {
max-width: 100%;
width: 300px;
position: relative;
z-index: 1;
}
.trivia-timer {
width: 550px;
max-width: 100%;
height: 20px;
border-radius: 3em;
margin-bottom: 50px;
padding: 5px 6px;
}
.trivia-timer span {
display: inline-block;
background: linear-gradient(90deg, #fff, #06c);
height: 10px;
vertical-align: top;
border-radius: 3em;
animation: progressbar-countdown;
animation-duration: 10s;
animation-iteration-count: 1;
animation-fill-mode: forwards;
animation-play-state: paused;
animation-timing-function: linear;
}
#keyframes progressbar-countdown {
0% {
width: 100%;
}
100% {
width: 0%;
}
}
.trivia-question {
margin-bottom: 50px;
}
.how-to-play-screen .default-button {
margin-bottom: 60px;
margin-top: 30px;
}
.button-container {
display: flex;
flex-wrap: wrap;
margin-bottom: 50px;
width: 600px;
max-width: 100%;
}
.button-outer {
flex-basis: 100%;
text-align: center;
margin-bottom: 20px;
max-width: 100%;
}
.default-button {
background: #333333;
border-radius: 3em;
font-family: 'Verdana', cursive;
font-size: 18px;
color: #fff;
letter-spacing: 2.45px;
padding: 10px 8px;
text-transform: uppercase;
transition: background .2s;
outline: none;
width: 250px;
cursor: pointer;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 100%;
}
.default-button:hover {
background: #222;
}
.default-button[disabled] {
background: transparent;
color: #222;
cursor: default;
}
.default-button[disabled]:hover {
background: transparent;
}
.default-button.correct {
cursor: default;
background: #2bb24a;
color: #fff;
}
.default-button.correct:hover {
background: #2bb24a;
color: #fff;
}
.default-button.wrong {
cursor: default;
background: #F6484C;
color: #fff;
}
.default-button.wrong:hover {
background: #F6484C;
color: #fff;
}
.title {
font-size: 32px;
margin-top: 100px;
}
.text {
line-height: 24px;
font-size: 16px;
font-family: 'Verdana', sans-serif;
text-align: center;
color: #ffffff;
text-transform: none;
}
.trivia-logo {
position: absolute;
bottom: 20px;
}
.trivia-corner-logo {
position: absolute;
left: 0;
top: 15px;
width: 100px;
}
.close-button {
position: absolute;
top: 50px;
right: 0;
background: transparent;
border: none;
color: #fff;
font-family: 'Verdana', cursive;
font-size: 34px;
outline: none;
text-transform: none;
cursor: pointer;
transition: color .2s;
}
.close-button:hover {
color: #eee;
}
.score-name {
margin: 0 0 28px;
font-size: 46px;
}
.score {
font-size: 18px;
margin-bottom: 10px;
}
.description {
text-align: center;
font-family: Verdana, sans-serif;
font-size: 16px;
color: #fff;
text-transform: none;
line-height: 24px;
display: inline-block;
margin-bottom: 30px;
}
#media screen and (min-width: 700px) {
.screen-section {
padding: 50px;
}
.button-outer {
flex-basis: 50%;
}
}
<div class="container">
<div class="wrapper">
<div class="screen-section main-screen">
<div class="trivia-image-wrapper">
<img alt="LOGO" src="./assets/Game-Logo.png" class="trivia-image">
</div>
<h1>Trivia</h1>
<div class="button-container">
<div class="button-outer">
<button class="default-button" id="play" type="button">Play</button>
</div>
<div class="button-outer">
<button class="default-button" id="how-to-play-button" type="button">How to play?</button>
</div>
</div>
<div class="trivia-logo">
<img alt="logo" src="./assets/-Logo.png">
</div>
</div>
<div class="screen-section hidden how-to-play-screen">
<img alt="LOGO" src="./assets/Game-Logo.png" class="trivia-corner-logo">
<button class="close-button" id="close-how-to" type="button">X</button>
<h2 class="title">How to Play</h2>
<p>Answer questions to score points.</p>
<button class="default-button" id="lets-start" type="button">Ok. Let's start</button>
<div class="trivia-logo">
<img alt="logo" src="./assets/-Logo.png">
</div>
</div>
<div class="screen-section hidden trivia-screen">
<div class="trivia-screen-step"><span id="question-index">1</span> out of <span id="question-count">10</span></div>
<div class="trivia-image-wrapper">
<p id="question-placement"></p>
</div>
<div class="trivia-timer" id="progress-bar"></div>
<div class="trivia-question" id="trivia-text"></div>
<div class="button-container" id="answers-container">
<div class="button-outer">
<button class="default-button" id="answer0" type="button"></button>
</div>
<div class="button-outer">
<button class="default-button" id="answer1" type="button"></button>
</div>
<div class="button-outer">
<button class="default-button" id="answer2" type="button"></button>
</div>
<div class="button-outer">
<button class="default-button" id="answer3" type="button"></button>
</div>
</div>
<div class="trivia-logo">
<img alt="logo" src="./assets/-Logo.png">
</div>
</div>
<div class="screen-section hidden result-screen">
<div class="trivia-image-wrapper">
<img alt="Trivia LOGO" src="./assets/Game-Logo.png" class="trivia-image">
</div>
<p class="score"><span id="score">0</span> out of <span id="score-total">10</span></p>
<h1 class="score-name" id="score-name">Trivia</h1>
<span class="description">you will learn more.</span>
<button class="default-button" id="play-again" type="button">Play again</button>
<div class="trivia-logo">
<img alt=" logo" src="./assets/-Logo.png">
</div>
</div>
</div>
</div>

Related

The Filter-function in my Recipe-App is not possible

I have developed a small recipe app. This one uses the edamame api for it. I have implemented a filter function which should filter by criteria like diet and health. In addition, it should also be possible to filter by calories. For this, the user specifies the maximum number of calories, if he wants to filter by calories. However, the filter function does not work. I enter the term "high protein" for the filter "health", and the term "burger" in the searchbar. But the result isn't filtered. The code looks functional to me. I hope you guys can help me out!
This is my HTML-Code:
<!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>Kitchn - Kochen leicht gemacht! </title>
<link href="styles.css" rel="stylesheet">
</head>
<body>
<main class="container">
<div style="text-align: center;">
<e style="margin: 0;" data-i18n-key="languages-title">Sprachen</e>
<div id="languages" class="grid">
<div id="de"></div>
<div id="en"></div>
</div>
<div class = "container" >
<div class = "row" id="photo"><!--collage-->
<div class="col-12" id="logo">
<img src="assets\image-removebg-preview.png" id= "food" class="row"/>
<div><p data-i18n-key="title" id="title">AppName</p></div>
</div>
</div>
</div>
<div class="row" id="search"><!--searchbar-->
<div class="col-8" id="searchbar" >
<img src = "assets\pawprint.png" id="paw"/>
<input placeholder="Vegan, etc." id="input"/>
</div>
<div class="col-2" id="button" >
<img src = "assets\paw.png" id="enter"/>
</div>
</div>
<div class ="row"id = "cards"><!--reccommedned-->
</div> <!--Filterfunktion für Kalorien etc. hier -->
<div class="row" id="filter">
<div class="col-3">
<select id="filter-select">
<option value="diet">Diät</option>
<option value="health">Gesundheit</option>
</select>
</div>
<div class="col-3">
<input type="text" id="filter-value" placeholder="Wert eingeben">
</div>
<div class="col-3">
<button id="submit" onclick="filterRecipes()">Filter anwenden</button>
</div>
<div class="col-3">
<div>Maximale Kalorien:</div>
<input type="text" id="calorie-limit" placeholder="Max. Kalorien">
</div>
</div>
</div>
<script src ="script.js"></script>
</body>
</html>
This is my JavaScript-Code:
const queryBox = document.getElementById("input");
const submit = document.getElementById("button");
submit.addEventListener("click", async function() {
const query = queryBox.value;
const recipes = await getRecipes(query);
useApiData(recipes);
});
document.addEventListener("keypress", async function(e) {
if (e.key === "Enter") {
const query = queryBox.value;
const recipes = await getRecipes(query);
useApiData(recipes);
}
});
const appId = "a59a7160";
const apiKey = "69e96203434da5104b731b2fd8a597b7";
async function getRecipes(query, from = 0, to = 8, diet = [], health = [], maxCalories = Number.POSITIVE_INFINITY) {
let url =`https://api.edamam.com/search?q=${query}&app_id=${appId}&app_key=${apiKey}&from=${from}&to=${to}`
if (diet.length) {
const dietString = diet.join(",");
url+=`&diet=${encodeURIComponent(dietString)}`
}
if (health.length) {
const healthString = health.join(",")
url+=`&health=${encodeURIComponent(healthString)}`
}
if (maxCalories !== Number.POSITIVE_INFINITY) {
url+= `&calories=${maxCalories.toString()}`
}
const response = await fetch(
url
);
const data = await response.json();
return data.hits;
}
function useApiData(data) {
const filteredRecipes = filterRecipes(data);
let toadd = "";
for (let i = 0; i < filteredRecipes.length; i++) {
let diet = "No Data Found";
if (data[i].recipe.dietLabels && Array.isArray(data[i].recipe.dietLabels) && data[i].recipe.dietLabels.length > 0) {
diet = data[i].recipe.dietLabels;
}
let health = "No restrictions";
if (data[i].recipe.healthLabels && Array.isArray(data[i].recipe.healthLabels) && data[i].recipe.healthLabels.length > 0) {
health = data[i].recipe.healthLabels;
}
toadd += `
<div class="card">
<img src="${data[i].recipe.image}" class="card-ing-top" alt="..."/>
<div class="card-body">
<h5 class="card-title">${data[i].recipe.label}</h5>
<b>Click here for full recipe! </b>
<br>
<br>
<r class = "item-data"><b>Calories: </b> <br> ${data[i].recipe.calories.toFixed(2)}</r>
<br>
<r class="item-data"><b>Diet label: </b> <br> ${diet}</r>
<br>
<r class = "item-data"><b>Health label: </b> <br> ${health}</r>
<br>
<r class = "item-data"><b>Ingredient line:</b> <br> ${data[i].recipe.ingredientLines}</r>
</div>
</div>
`
}
document.getElementById("cards").innerHTML = toadd;
}
function filterRecipes(recipes, diet = [], health = []) {
if (diet.length === 0 && health.length === 0) {
return recipes;
}
const filteredRecipes = recipes.filter((recipe) => {
if (diet.length > 0 && recipe.recipe.dietLabels) {
const dietLabels = recipe.recipe.dietLabels.map((label) => label.toLowerCase());
if (!diet.some((d) => dietLabels.includes(d))) {
return false;
}
}
if (health.length > 0 && recipe.recipe.healthLabels) {
const healthLabels = recipe.recipe.healthLabels.map((label) => label.toLowerCase());
if (!health.some((h) => healthLabels.includes(h))) {
return false;
}
}
return true;
});
return filteredRecipes;
}
//Language code
let exceeded = "You have exceeded the MONTHLY quota for Characters on your current plan, BASIC. Upgrade your plan at https://rapidapi.com/googlecloud/api/google-translate1"
const defaultLocale = navigator.language.slice(0,2)
let locale
let translations = {}
document.addEventListener("DOMContentLoaded", () => {
setLocale(defaultLocale)
bindLocaleSwitcher(defaultLocale)
})
function translateElement(element){
const key = element.getAttribute("data-i18n-key")
const translation = translations[locale][key]
element.innerText = translation
}
async function setLocale(newLocale){
if(newLocale===locale) return
const newTranslations = await fetchTranslationsFor(newLocale)
locale = newLocale
translations = newTranslations
translatePage()
}
async function fetchTranslationsFor(newLocale){
const response = await fetch(`/lang/${newLocale}.json`)
return await response.json()
}
function translatePage(){
document.querySelectorAll("[data-i18n-key]").forEach(translateElement)
}
function translateElement(element){
const key = element.getAttribute("data-i18n-key")
const translation = translations[key]
element.innerText = translation
}
function bindLocaleSwitcher(initialValue){
const switcher = document.getElementById("languages").children
for(const sw of switcher){
sw.addEventListener('click', () => {
setLocale(sw.id)
input.value = ""
results.innerHTML = ""
})
}
}
This is my CSS-Code:
#import url('https://fonts.googleapis.com/css2?family=Grand+Hotel&display=swap');
#import url('https://fonts.googleapis.com/css2?family=Montserrat:wght#500;700&display=swap');
.container{
background-color: #FDEEDC;
}
body{
margin: 0;
padding: 0;
background-color: #FDEEDC;
}
#languages{
display: flex;
justify-content: center;
margin-bottom: 15px;
}
#languages > div{
background-repeat: no-repeat;
background-position: center;
background-size: 180%;
border-radius: 999px;
width: 30px;
height: 30px;
margin-left: 2vh;
margin-top: 2vh;
transition: all .2s;
}
#languages > div:hover{
filter: brightness(105%);
background-size: 220%;
transition: all .2s;
}
#languages > div:active{
filter: brightness(85%);
}
#de{
background: url('svg/Flag_of_Germany.svg');
}
#en{
background: url('svg/gb.svg');
}
/* TEST ende */
#photo{
background-color: #FDEEDC;
height: 50vh;
}
#search{
position: absolute;
z-index: 1;
width: 100%;
height: 78px;
align-items: center;
justify-content: center;
display: flex;
top: 0;
margin-top: 57vh;
background-color: #FDEEDC;
}
#searchbar{
background-color: #FFC3A1;
width: 70%;
height: 80px;
align-items: center;
border-radius: 60px;
margin-right: 10px;
justify-content: center;
display: flex;
}
#button{
background-color: #FDEEDC;
}
#cards{
background-color: #FDEEDC;
margin-top: 100px;
}
#food{
height: 22%;
width:22% ;
align-items: center;
justify-content: center;
display: flex;
padding-top: 7px;
}
#logo{
align-items: center;
justify-content: center;
display: flex;
margin: auto;
}
#input{
width: 90%;
font-size: 28px;
border: 0;
background-color: #FFC3A100;
color: #FDEEDC;
}
#paw{
width: 9vh;
height: 9vh;
transform: scaleX(-1);
margin-left: 15px;
margin-right: 10px;
}
#input:focus{
outline: none;
}
p{
font-family: 'Grand Hotel', cursive;
font-size: 70px;
}
r{
font-family: 'Times New Roman';
font-size: 20px;
}
e{
font-family: 'Grand Hotel', cursive;
font-size: 30px;
}
#enter{
height: 8vh;
width: 8vh;
margin-left: 1vh;
background-color: #F0997D;
border-radius: 70px;
transition: 300ms;
}
#enter:hover{
cursor: pointer;
background-color: #F2B4B4;
background-size: 220%;
transition: all .2s;
}
.card{
border-radius: 10px;
border:10px solid #F2B4B4;
width:300px;
padding: 10px;
background-color: #FFDECF;
margin: 20px;
float: left;
height: 1000px;
}
.card-ing-top{
height: 300px;
width: 300px;
object-fit: cover;
border-radius: 10px;
}
.card-title{
font-family: Montserrat;
font-size: 20px;
}
.btn{
text-decoration: none;
font-family: Montserrat;
font-weight: 400;
color: #A75D5D;
}
In my localhost, I checked the functions of my app. I entered a term like "burer" in the search bar and "high-protein" as filter for health and pressed the search button. However, the filterfunction for the search doesn't work, meaning the get doesn't work and I don't get any filtered recipes back based on my search.
It looks like your API query string is incorrect and it returns a 400 error.
For example, if you remove the last parameter (e.g. &calories=), then the response is good. Check in the documentation.

How to check if all dom-elements in an object containing a value

I saved all dom-elements in an object. I want that my Script is able to check every time when there is some input if all input fields are empty anymore. If yes, the button should still be disabled, otherwise the forward button is enabled and the user can click to the next page.
Ways like like using querySelectorAll input field etc. are working but I want that this is working with using the object.
The "areTruthy" variable is directly true if one input field is not empty anymore but it should only be true if all input fields are true. Where is my code wrong?
window.onload = () => {
forward = document.getElementById("forward");
input = {
caseNumber: {
month: document.getElementById("month"),
year: document.getElementById("year"),
},
clientsInformation: {
gender: document.getElementById("gender"),
inpName: document.getElementById("inpName"),
},
adress: {
street: document.getElementById("street"),
houseNumber: document.getElementById("house-number"),
postCode: document.getElementById("postCode"),
city: document.getElementById("city"),
receiver: document.getElementById("receiver"),
},
};
addEventListener("input", () => {
for (parts in input) {
const areTruthy = Object.values(input[parts]).every((value) => value != "");
if (areTruthy) {
forward.style.backgroundColor = "rgb(77,55,120)";
forward.style.color = "white";
forward.disabled = false;
forward.style.transition = "1s ease";
forward.addEventListener("click", () => {
window.open("case.html");
});
} else {
forward.style.backgroundColor = "rgb(191,191,191)";
forward.style.color = "black";
forward.disabled = true;
}
}
});
};
<body>
<h3>Fill in all fields</h3>
<div id = "wrapper">
<div id = "caseNumber">
<label id = "caseLabel"></label>
<input id = "month" placeholder="Zahlenfolge">
<input id = "year" placeholder = "Jahr">
</div>
<div id = "name">
<label for = "name">Name</label>
<select id = "gender">
<option>Herr</option>
<option>Frau</option>
</select>
<input id = "inpName" placeholder = "Name">
</div>
<div id = "adress">
<label for = "adress">Adresse</label>
<div id = "adressWrapper1">
<input placeholder = "Straße" id = "street" >
<input placeholder = "Hausnummer" id = "house-number">
<input placeholder = "Postleitzahl" id = "postCode" >
</div>
<div id = "adressWrapper2">
<input placeholder = "Stadt" id = "city" >
<input placeholder = "Adressant" id = "receiver" >
</div>
</div>
</div>
</div>
<div class = "button-bar">
<div class = "nav-inner" id = "backward"><a class = "nav-inner" href= "#http://127.0.0.1:5500/pages/client.html" ></a> < Zurück</div>
<div class = "nav-inner" id = "forward"> Weiter ></div>
</div>
</body>
</html>
.navbar {
display: flex;
list-style: none;
background-color: rgb(77, 55, 120);
margin: 0;
position: fixed;
width: 100%;
gap: 4rem;
height: 50px;
text-align: center;
line-height: 45px;
left: 0;
top: 0;
}
.nav-text {
text-decoration: none;
color: white;
width: auto;
cursor: pointer;
font-size: 18px;
padding-bottom: 5px;
}
#wrapper {
margin-top: 10rem;
margin-left: 5rem;
display: sticky;
}
#caseNumber {
display: block;
}
input::placeholder {
font-size: 1rem;
text-align: center;
line-height: 19rem;
}
.button-bar {
position: fixed;
bottom: 0;
width: 100%;
display: flex;
margin: 0;
left: 0;
}
.nav-inner {
cursor: pointer;
width: 50%;
text-align: center;
line-height: 83px;
}
#backward {
background-color: rgb(101, 93, 93);
color: white;
}
#forward {
background-color: rgb(191, 191, 191);
}
h3 {
left: 20vh;
position: absolute;
font-size: 24px;
margin-top: 0.5rem;
}
#caseNumber {
position: absolute;
left: 20vh;
margin-top: 6.5rem;
text-align: left;
}
#name {
position: absolute;
left: 20vh;
margin-top: 12.5rem;
}
label {
display: inline-block;
text-align: left;
width: 140px;
font-size: 20px;
}
input,
select {
width: 30vh;
height: 5vh;
font-size: 19px;
border-radius: 5px;
border-style: solid;
border: 1px solid;
}
#adress {
position: absolute;
left: 20vh;
margin-top: 18.5rem;
max-width: 40rem;
display: block;
}
#adressWrapper1 {
display: flex;
gap:5vh;
flex-direction: column;
left: 18vh;
position: absolute;
top:0rem
}
#adressWrapper2 {
display: flex;
gap:5vh;
flex-direction: column;
position: absolute;
left: 50vh;
top:0rem
}
You are not checking input values. Also you are only checking every on child per parent object key, not on all children together so you need to lift if outside for
addEventListener("input", () => {
let allFilled = true;
for (parts in input) {
const anyEmpty = Object.values(input[parts]).some(el => el.value == "");
if (anyEmpty) {
allFilled = false;
break;
}
}
if (allFilled) {
forward.style.backgroundColor = "rgb(77,55,120)";
forward.style.color = "white";
forward.disabled = false;
forward.style.transition = "1s ease";
forward.addEventListener("click", () => {
window.open("case.html");
});
} else {
forward.style.backgroundColor = "rgb(191,191,191)";
forward.style.color = "black";
forward.disabled = true;
}
});
};
If you want to see what is exactly happening you can use this to log
const anyEmpty = Object.values(input[parts]).some((el) => {
console.log(el, el.value, el.value == "");
return el.value == "";
});

When i click the next or previous the thumbnail's are not changed

its an image slider when I click the next I needs to change the image in the thumbnails also but its not working. also not showing main picture when I click in the the first picture and the second is working but third also not working...
thumbnail's are not change through next and previous...
in slider images are change through next and previous but the thumbnails are not change with image...
Code.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<style>
.newsslider {
width: 100%;
height: 800px;
background-color:#766582;
}
.text {
text-align: center;
font-size: 40px;
color: white;
margin-bottom: -101px;
}
.btn1,
.btn2 {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
margin-top: -30px;
padding: 16px;
color: #52492f;
font-weight: bold;
font-size: 20px;
border-radius: 0 3px 3px 0;
user-select: none;
}
.btn2 {
position: absolute;
right: 0;
border-radius: 3px 0 0 3px;
}
.btn1:hover,
.btn2:hover {
background-color: rgba(0, 0, 0, 0.8);
color: white;
}
.onebtn {}
.twobtn {}
.thumbs {
display: flex;
padding-top: 6%;
align-items: center;
justify-content: center;
list-style: none;
}
.thumbs li {
width: 12%;
padding: 10px;
margin: 1%;
}
.thumbs li img {
width: 100%;
}
.img12:hover {
box-shadow: 0 0 2px 1px rgba(0, 140, 186, 0.5);
}
</style>
</head>
<body>
<div class="newsslider">
<p class="text" id="demo"><img id="demo1" src="img5.png" width=30%; height=400px;> </p>
<div class="onebtn">
<button id="btn1" class="btn1" type="button" class="prev" onclick="prev()">PREV</button>
</div>
<div class="twobtn">
<button id="btn2" class="btn2" type="button" class="next" onclick="next()">NEXT</button>
</div>
<p id="newsArr1" class="text" style="font-size:40px; font-weight:bolder; color: #521d2c;">Hi,</p>
<ul class="thumbs">
<li class="img12" onclick="thumbchange(1)"><img src="img5.png" width=500%;></li>
<li class="img12" onclick="thumbchange(2)"><img src="img2.png"></li>
<li class="img12" onclick="thumbchange(3)"><img src="img4.png"></li>
</ul>
</div>
<script>
var newsArr = ['<img src="img5.png"width = 30%; height=400px;>',
'<img src="img2.png"width = 30%; height=400px; >',
'<img src="img4.png" width = 30%; height=400px;>'];
var newsArr1 = ["Hi",
"This is Urraan",
"Urraan is a digital gateway"];
var i = 0;
var x = document.getElementById("demo");
var y = document.getElementById("newsArr1");
// var timeoutId;
function next() {
// if (timeoutId) {
// clearTimeout(timeoutId);
// }
i++;
if (i < newsArr.length) {
x.innerHTML = newsArr[i];
y.innerHTML = newsArr1[i];
} else {
i = 0;
x.innerHTML = newsArr[i];
y.innerHTML = newsArr1[i];
}
// timeoutId = setTimeout(next, 2000);
}
function prev() {
i--;
if (i >= 0) {
x.innerHTML = newsArr[i];
y.innerHTML = newsArr1[i];
} else {
i = newsArr.length - 1;
x.innerHTML = newsArr[i];
y.innerHTML = newsArr1[i];
}
}
function thumbchange(num) {
var thumb = 'img' + num + '.png';
document.getElementById("demo1").src = thumb;
}
</script>
</body>
</html>
you problem solved ... please try it.
var newsArr = ['<img src="https://www.w3schools.com/bootstrap4/la.jpg"width = 100%; height=400px;>',
'<img src="https://www.w3schools.com/bootstrap4/chicago.jpg"width = 100%; height=400px; >',
'<img src="https://www.w3schools.com/bootstrap4/ny.jpg" width = 100%; height=400px;>'];
var newsArr1 = ["Hi",
"This is Urraan",
"Urraan is a digital gateway"];
var i = 0;
var x = document.getElementById("demo");
var y = document.getElementById("newsArr1");
// var timeoutId;
function next() {
// if (timeoutId) {
// clearTimeout(timeoutId);
// }
i++;
if (i < newsArr.length) {
x.innerHTML = newsArr[i];
y.innerHTML = newsArr1[i];
} else {
i = 0;
x.innerHTML = newsArr[i];
y.innerHTML = newsArr1[i];
}
// timeoutId = setTimeout(next, 2000);
setThumbnailFocus(i)
}
function prev() {
i--;
if (i >= 0) {
x.innerHTML = newsArr[i];
y.innerHTML = newsArr1[i];
} else {
i = newsArr.length - 1;
x.innerHTML = newsArr[i];
y.innerHTML = newsArr1[i];
}
setThumbnailFocus(i)
}
function thumbchange(num) {
x.innerHTML = newsArr[num-1];
y.innerHTML = newsArr1[num-1];
setThumbnailFocus(num-1)
}
function setThumbnailFocus(num){
var elems = document.querySelectorAll(".thumbs .selected");
[].forEach.call(elems, function(el) {
el.classList.remove("selected");
});
document.getElementsByClassName("img12")[num].classList.add("selected");
}
.newsslider {
width: 100%;
height: 800px;
background-color:#766582;
}
.text {
text-align: center;
font-size: 40px;
color: white;
margin-bottom: -101px;
}
.btn1,
.btn2 {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
margin-top: -30px;
padding: 16px;
color: #52492f;
font-weight: bold;
font-size: 20px;
border-radius: 0 3px 3px 0;
user-select: none;
}
.btn2 {
position: absolute;
right: 0;
border-radius: 3px 0 0 3px;
}
.btn1:hover,
.btn2:hover {
background-color: rgba(0, 0, 0, 0.8);
color: white;
}
.onebtn {}
.twobtn {}
.thumbs {
display: flex;
padding-top: 6%;
align-items: center;
justify-content: center;
list-style: none;
}
.thumbs li {
width: 12%;
padding: 10px;
margin: 1%;
}
.thumbs li img {
width: 100%;
}
.img12:hover {
box-shadow: 0 0 2px 1px rgba(0, 140, 186, 0.5);
}
.selected{
border:solid 2px red
}
<div class="newsslider">
<p class="text" id="demo"><img id="demo1" src="https://www.w3schools.com/bootstrap4/la.jpg" width=100%; height=400px;> </p>
<div class="onebtn">
<button id="btn1" class="btn1" type="button" class="prev" onclick="prev()">PREV</button>
</div>
<div class="twobtn">
<button id="btn2" class="btn2" type="button" class="next" onclick="next()">NEXT</button>
</div>
<p id="newsArr1" class="text" style="font-size:40px; font-weight:bolder; color: #521d2c;">Hi,</p>
<ul class="thumbs">
<li class="img12 selected" onclick="thumbchange(1)"><img src="https://www.w3schools.com/bootstrap4/la.jpg" width=500%;></li>
<li class="img12" onclick="thumbchange(2)"><img src="https://www.w3schools.com/bootstrap4/chicago.jpg"></li>
<li class="img12" onclick="thumbchange(3)"><img src="https://www.w3schools.com/bootstrap4/ny.jpg"></li>
</ul>
</div>
The first issue I found is that you have this code:
<p class="text" id="demo"><img id="demo1" src="img5.png" width=30%; height=400px;> </p>
And here you didn't use part with setting id:
var newsArr = ['<img //here is no id// src="img5.png"width = 30%; height=400px;>',
'<img //here is no id// src="img2.png"width = 30%; height=400px; >',
'<img //here is no id// src="img4.png" width = 30%; height=400px;>'];
And when you are clicking on next and prev button, you are removing your id unconsciously, so your thumbchange() function stop working, because it is based on id.

How to position a h1 directly over an input and have it be for all screens?

So I want to replace the text inside of an input field with a h1 tag as soon as the user hits submit because i want the text to have an animation but i can't animate the text inside the text field.
I linked the code pen project version of it to make it easier then organizing all the code in here. I added all the code I had so I wouldn't leave anything out although some of it may be irrelevant.
Basically I want the h1 tag to appear exactly where the input text was so it looks like nothing ever got replaced.
https://codepen.io/timvancowabunga/pen/rNOqdYd
$(document).ready(function() {
$('#btn1').click(function() {
$('#test').text($("#message").val());
$('#message').val('');
$('#test').val('');
});
});
function onTextClick() {
document.getElementById('btn1').className = "show";
}
function showButton() {
document.getElementById('btn1').style.display = 'block';
}
function showSendButton() {
document.getElementById('btn2').style.display = 'block';
}
function formCheck() {
var input = $('#message').val();
if (input == '') {
alert("Please Submit a Valid Message");
} else {
hideButton();
showSendButton();
}
}
function hideButton() {
document.getElementById('btn1').style.display = 'none';
}
function hideSendButton() {
document.getElementById('btn2').style.display = 'none';
document.getElementById('sent').style.display = 'block';
}
function myMove() {
var textWrapper = document.querySelector('.ml13');
textWrapper.innerHTML = textWrapper.textContent.replace(/\S/g, "<span class='letter'>$&</span>");
anime.timeline()
.add({
targets: '.ml13 .letter',
translateY: [0, -1600],
opacity: [1, 0],
easing: "easeInSine",
duration: 3600,
delay: (el, i) => 800 + 60 * i
});
}
body {
background-color: #368670;
font-family: sans-serif;
}
.ml13,
.ml14,
.ml15 {
font-size: 1.9em;
text-transform: uppercase;
letter-spacing: 0.2em;
font-weight: 600;
}
.ml15 {
letter-spacing: 0em;
text-align: center;
}
.ml13 .letter {
display: inline-block;
line-height: 1em;
}
.line {
display: flex;
margin: auto;
width: 50%;
margin-top: 500px;
}
.wrappy {
position: relative;
}
.wrappy h1 {
position: absolute;
left: 48.5%;
top: 20%
}
.butt {
padding-top: 50px;
display: flex;
margin: 0 auto;
width: 100%;
}
#btn1,
#btn2 {
display: table;
margin: 0 auto;
}
input {
z-index: 1000;
margin-left: 10%;
width: 80%;
background: transparent;
border: 0;
border-bottom: 1px solid;
padding: 1em 0 .1em;
text-align: center;
font-size: 18px;
font-family: inherit;
font-weight: 300;
line-height: 1.5;
color: inherit;
outline: none;
}
input:focus {
border-color: #ffffff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.0.2/anime.min.js"></script>
<div class="truth">
<!-- <div class="line"> -->
<div class="message-box">
<form class="message-form">
<h2 class="ml15" for="message">TELL A TRUTH</h2>
<div class="wrappy">
<input type="text" id="message" name="message" autocomplete="off" class="ml14">
<!-- <h1 id="test" class="ml13">I love your music!</h1> -->
<h1 id="test" class="ml13"></h1>
</div>
</form>
</div>
<div class="butt">
<button id="btn1" onclick="formCheck();">Ready to Send?</button>
<button id="btn2" style="display: none" onclick="myMove(); setTimeout(showButton, 3000); hideSendButton();">Send!</button>
</div>
</div>
You want to put H1 below the input.
Then you make the text input transparent. Bind the input value to h1.
So in effect when user clicks and type, they are selecting the input and changing its value, but it's transparent, to be shown by the h1 below the input that you will eventually animate.
Also because you mentioned you want it to display correctly in all platforms. You then have to be cognisant of the default behaviours of DOM and CSS properties. If you alter them to get what you want without knowing its natural order, you can get unexpected behaviour and reduce cross-browser compatibility. I have made changes to reflect that.
$(document).ready(function () {
$("#btn1").click(function () {
$("#test").text($("#message").val());
$("#message").val("");
$("#test").val("");
});
});
function onTextClick() {
document.getElementById("btn1").className = "show";
}
function showButton() {
document.getElementById("btn1").style.display = "block";
}
function showSendButton() {
document.getElementById("btn2").style.display = "block";
}
function formCheck() {
var input = $("#message").val();
if (input == "") {
alert("Please Submit a Valid Message");
} else {
hideButton();
showSendButton();
}
}
function hideButton() {
document.getElementById("btn1").style.display = "none";
}
function hideSendButton() {
document.getElementById("btn2").style.display = "none";
document.getElementById("sent").style.display = "block";
}
// attach this to bind h1 to the input value at all times.
$("#message").keyup(function () {
var self = this;
$("#test").text($(this).val());
});
function myMove() {
var textWrapper = document.querySelector(".ml13");
textWrapper.innerHTML = textWrapper.textContent.replace(
/\S/g,
"<span class='letter'>$&</span>"
);
anime.timeline().add({
targets: ".ml13 .letter",
translateY: [0, -1600],
opacity: [1, 0],
easing: "easeInSine",
duration: 3600,
delay: (el, i) => 800 + 60 * i
});
}
body {
background-color: #368670;
font-family: sans-serif;
}
.ml13,
.ml14,
.ml15 {
font-size: 1.9em;
text-transform: uppercase;
letter-spacing: 0.2em;
font-weight: 600;
}
.ml15 {
letter-spacing: 0em;
text-align: center;
}
.ml13 .letter {
display: inline-block;
line-height: 1em;
}
.line {
display: flex;
margin: auto;
width: 50%;
margin-top: 500px;
}
.wrappy {
position: relative;
text-align: center;
}
.wrappy h1 {
position: absolute; /* you then want to give wrappy h1 this to make it occupy no space. */
width: 100%; /* to centralize the text, your option here is to make this 100% width and use text-align */
text-align: center;
padding-top: 21px;
}
.butt {
padding-top: 50px;
display: flex;
margin: 0 auto;
width: 100%;
}
#btn1,
#btn2 {
display: table;
margin: 0 auto;
}
input {
position: relative; /* in order for z-index to work, you need to give an element `position` attribute of value `static`, `relative` or `absolute`. */
z-index: 1000; /* now this will work. wrappy h1 is not given a `z-index` so it defaults to `1`, hence input will be on top of wrappy h1 now. */
width: 80%;
background: transparent;
border: 0;
border-bottom: 1px solid #000; /* you need the line back because we are going to assign color to be transparent */
padding: 35px 0 0 0;
text-align: center;
font-size: 18px;
font-family: inherit;
font-weight: 300;
line-height: 1.5;
color: transparent; /* make the text transparent */
outline: none;
}
input:focus {
border-color: #ffffff;
}
<div class="truth">
<!-- <div class="line"> -->
<div class="message-box">
<form class="message-form">
<h2 class="ml15" for="message">TELL A TRUTH</h2>
<div class="wrappy">
<!-- for natural flow, you want to shift #test to above the input, so that input can stack on top of it -->
<h1 id="test" class="ml13"></h1>
<input type="text" id="message" name="message" autocomplete="off" class="ml14">
<!-- <h1 id="test" class="ml13">I love your music!</h1> -->
</div>
</form>
</div>
<div class="butt">
<button id="btn1" onclick="formCheck();">Ready to Send?</button>
<button id="btn2" style="display: none" onclick="myMove(); setTimeout(showButton, 3000); hideSendButton();">Send!</button>
</div>
</div>

How to add a textarea to the image preview when uploading

I've been struggling with this problem 3 entire days. Any help would be appreciated!
I have a button 'ADD MY PHOTO' and when clicked, it comes a popup with the option to upload a picture or more. So, when I click 'Select Files' button or I drag & drop a picture or more, it will preview the pictures on the right side.
What I need help with is: when I upload a picture or 2, I want on the right side of every picture to display a textarea where the user can write something (like a caption). Also, after the pictures and captures are displayed I need the option to remove one or all of them. Here is a picture:
Here is the CodePen code: https://codepen.io/anon/pen/VEQMwm
Thanks in advance for help.
Also, here is the code:
// ---------- THIS IS FOR THE POPUP ---------- //
function CustomAlert() {
this.performCustomAlert = function (dialog) {
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
var dialogoverlay = document.getElementById('dialogoverlay');
var dialogbox = document.getElementById('dialogbox');
dialogoverlay.style.display = "block";
dialogoverlay.style.height = windowHeight + "px";
dialogbox.style.display = "block";
}
this.ok = function () {
document.getElementById('dialogbox').style.display = "none";
document.getElementById('dialogoverlay').style.display = "none";
}
}
var newAlert = new CustomAlert();
// ------------- TABS ----------------- //
function openTab(evt, tabName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(tabName).style.display = "block";
evt.currentTarget.className += " active";
}
document.getElementById("defaultOpen").click();
// ---------------- UPLOAD --------------------------//
// ************************ Drag and drop ***************** //
let dropArea = document.getElementById("drop-area")
// Prevent default drag behaviors
;['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
dropArea.addEventListener(eventName, preventDefaults, false)
document.body.addEventListener(eventName, preventDefaults, false)
})
// Highlight drop area when item is dragged over it
;['dragenter', 'dragover'].forEach(eventName => {
dropArea.addEventListener(eventName, highlight, false)
})
;['dragleave', 'drop'].forEach(eventName => {
dropArea.addEventListener(eventName, unhighlight, false)
})
// Handle dropped files
dropArea.addEventListener('drop', handleDrop, false)
function preventDefaults (e) {
e.preventDefault()
e.stopPropagation()
}
function highlight(e) {
dropArea.classList.add('highlight')
}
function unhighlight(e) {
dropArea.classList.remove('active')
}
function handleDrop(e) {
var dt = e.dataTransfer
var files = dt.files
handleFiles(files)
}
let uploadProgress = []
let progressBar = document.getElementById('progress-bar')
function initializeProgress(numFiles) {
progressBar.value = 0
uploadProgress = []
for(let i = numFiles; i > 0; i--) {
uploadProgress.push(0)
}
}
function updateProgress(fileNumber, percent) {
uploadProgress[fileNumber] = percent
let total = uploadProgress.reduce((tot, curr) => tot + curr, 0) / uploadProgress.length
console.debug('update', fileNumber, percent, total)
progressBar.value = total
}
function handleFiles(files) {
files = [...files]
initializeProgress(files.length)
files.forEach(uploadFile)
files.forEach(previewFile)
}
function previewFile(file) {
let reader = new FileReader()
reader.readAsDataURL(file)
reader.onloadend = function() {
let img = document.createElement('img')
img.src = reader.result
document.getElementById('gallery').appendChild(img)
}
}
function uploadFile(file, i) {
var xhr = new XMLHttpRequest()
var formData = new FormData()
xhr.open('POST', true)
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
// Update progress (can be used to show progress indicator)
xhr.upload.addEventListener("progress", function(e) {
updateProgress(i, (e.loaded * 100.0 / e.total) || 100)
})
xhr.addEventListener('readystatechange', function(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
updateProgress(i, 100) // <- Add this
}
else if (xhr.readyState == 4 && xhr.status != 200) {
// Error. Inform the user
}
})
formData.append('upload_preset', 'ujpu6gyk')
formData.append('file', file)
xhr.send(formData)
}
.add-photo{
width: 18%;
background-color: #00a100;
color: #fff;
padding: 11px 13px;
border: 3px solid #00a100;
-webkit-transition: 0.3s ease;
transition: 0.3s ease;
cursor: pointer;
text-align: center;
font-size: 13px;
font-weight: 550;
border-radius: 1px;
margin-left: 41%;
}
* {
box-sizing: border-box;
}
#dialogoverlay {
display: none;
opacity: 0.5;
/*so that user can see through it*/
position: fixed;
top: 0px;
left: 0px;
background: black;
z-index: 10;
height: 100%;
width: 100%;
}
#dialogbox {
display: none;
position: fixed;
background: #ffffff;
border-radius: 1px;
border: 0.5px solid #ccc;
z-index: 10;
left: 25%;
top: 20%;
width: 50%;
height: 400px;
-webkit-animation: fadeEffect 0.3s;
animation: fadeEffect 0.3s;
}
#close-popup {
float: right;
background-color: red;
color: #474747;
font-size: 15px;
}
.header{
position: absolute;
width: 100.2%;
background-color: white;
height: 11%;
top: 5.4%;
left: 50%;
transform: translate(-50%, -50%);
}
.content-centre{
width: 99%;
height: 77%;
margin-left: 3px;
margin-top: 46px;
}
#content-leftside{
width: 65%;
height: 100%;
float: left;
}
.tab {
overflow: hidden;
}
.tab button {
width: 33.3%;
height: 14%;
background-color: #acacac;
float: left;
color: white;
outline: none;
cursor: pointer;
padding: 6px;
transition: 0.3s;
border-right: 1px solid #fff;
}
.tab button:hover {
background-color: #474747;
}
.tab button.active {
background-color: #474747;
}
.tabcontent {
display: none;
padding: 6px 12px;
}
#content-rightside{
width: 35%;
height: 100%;
float: right;
background-color: #ffffff;
border-left: 1px solid #dddddd;
}
#right-topbar{
width: 100%;
height: 9%;
background-color: #474747;
color: #fff;
padding: 5px;
text-align: center;
transition: 0.3s;
}
.footer{
position: absolute;
width: 100.2%;
background-color: #474747;
height: 11%;
bottom: -5.6%;
left: 50%;
/* top: calc(50% - 50px); */
transform: translate(-50%, -50%);
}
/*------------------- UPLOAD AREA -----------------------*/
#drop-area {
border: 2px dashed #ccc;
border-radius: 8px;
width: 98%;
margin: 24px auto;
padding: 15px;
}
#progress-bar{
display: none;
}
#gallery {
margin-top: 5%;
}
#gallery img {
width: 55px;
height: 50px;
margin-bottom: 10px;
margin-left: 10px
}
.button {
display: inline-block;
padding: 10px;
background: #00a100;
color: #fff;
cursor: pointer;
border-radius: 5px;
}
#fileElem {
display: none;
}
#upload-button{
font-size: 40px;
color: #00a100;
<button class="add-photo" onclick="newAlert.performCustomAlert()">ADD MY PHOTO</button>
<div class="popup-upload">
<div id="dialogoverlay"></div>
<!--------------- SELECT MEDIA BOX ---------------->
<div id="dialogbox">
<!--------------- HEADER OF THE BOX ---------------->
<div class="header">
<!--------------- CLOSE POPUP ---------------->
<button id="close-popup" onclick="newAlert.ok()"><i class="fa fa-times" style="margin-top: 8px; margin-right: 7px;"></i></button>
<div class="select-media">
<i class="fa fa-camera" id="select-camera"></i>
<h2 id="select-media">SELECT YOUR MEDIA</h2>
</div>
</div>
<!--------------- CONTENT OF THE BOX ---------------->
<div class="content-centre">
<!--------------- LEFT CONTENT ---------------->
<div id="content-leftside">
<div class="tab">
<button class="tablinks" id="defaultOpen" onclick="openTab(event, 'Desktop')"><span class="fa fa-desktop"></span> Desktop</button>
<button class="tablinks" onclick="openTab(event, 'Facebook')"><span class="fa fa-facebook"></span> Facebook</button>
<button class="tablinks" onclick="openTab(event, 'Instagram')"><span class="fa fa-instagram"></span> Instagram</button>
</div>
<div id="Desktop" class="tabcontent">
<div id="drop-area">
<form class="my-form">
<span class="fa fa-cloud-upload" id="upload-button"></span>
<p id="drag-text">Drag & Drop Your <br> Photos or Videos <br> To Upload</p>
<input type="file" id="fileElem" multiple accept="image/*" onchange="handleFiles(this.files)">
<label class="button" for="fileElem">or Select Files</label>
</form>
</div>
</div>
<div id="Facebook" class="tabcontent">
<h3>Facebook</h3>
</div>
<div id="Instagram" class="tabcontent">
<h3>Instagram</h3>
</div>
</div>
<!--------------- RIGHT CONTENT ---------------->
<div id="content-rightside">
<!--------------- RIGHT TOPBAR ---------------->
<div id="right-topbar">
<h1>Selected Media</h1>
</div>
<progress id="progress-bar" max=100 value=0></progress>
<div id="gallery"/></div>
</div>
</div>
<div class="footer">
</div>
</div>
</div>
</div>
Look into below code, I made some changes on previewFile() function.
I hope, by looking below code you can get idea.
// ---------- THIS IS FOR THE POPUP ---------- //
function CustomAlert() {
this.performCustomAlert = function(dialog) {
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
var dialogoverlay = document.getElementById('dialogoverlay');
var dialogbox = document.getElementById('dialogbox');
dialogoverlay.style.display = "block";
dialogoverlay.style.height = windowHeight + "px";
dialogbox.style.display = "block";
}
this.ok = function() {
document.getElementById('dialogbox').style.display = "none";
document.getElementById('dialogoverlay').style.display = "none";
}
}
var newAlert = new CustomAlert();
// ------------- TABS ----------------- //
function openTab(evt, tabName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(tabName).style.display = "block";
evt.currentTarget.className += " active";
}
document.getElementById("defaultOpen").click();
// ---------------- UPLOAD --------------------------//
// ************************ Drag and drop ***************** //
let dropArea = document.getElementById("drop-area")
// Prevent default drag behaviors
;
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
dropArea.addEventListener(eventName, preventDefaults, false)
document.body.addEventListener(eventName, preventDefaults, false)
})
// Highlight drop area when item is dragged over it
;
['dragenter', 'dragover'].forEach(eventName => {
dropArea.addEventListener(eventName, highlight, false)
})
;
['dragleave', 'drop'].forEach(eventName => {
dropArea.addEventListener(eventName, unhighlight, false)
})
// Handle dropped files
dropArea.addEventListener('drop', handleDrop, false)
function preventDefaults(e) {
e.preventDefault()
e.stopPropagation()
}
function highlight(e) {
dropArea.classList.add('highlight')
}
function unhighlight(e) {
dropArea.classList.remove('active')
}
function handleDrop(e) {
var dt = e.dataTransfer
var files = dt.files
handleFiles(files)
}
let uploadProgress = []
let progressBar = document.getElementById('progress-bar')
function initializeProgress(numFiles) {
progressBar.value = 0
uploadProgress = []
for (let i = numFiles; i > 0; i--) {
uploadProgress.push(0)
}
}
function updateProgress(fileNumber, percent) {
uploadProgress[fileNumber] = percent
let total = uploadProgress.reduce((tot, curr) => tot + curr, 0) / uploadProgress.length
console.debug('update', fileNumber, percent, total)
progressBar.value = total
}
function handleFiles(files) {
files = [...files]
initializeProgress(files.length)
files.forEach(uploadFile)
files.forEach(previewFile)
}
function previewFile(file) {
let reader = new FileReader()
reader.readAsDataURL(file)
reader.onloadend = function() {
let img = document.createElement('img')
img.src = reader.result
var mainDiv = document.createElement("div")
mainDiv.className = "box"
mainDiv.appendChild(img)
var textbx = document.createElement("textarea")
textbx.placeholder ="Caption..."
mainDiv.appendChild(textbx)
var btn = document.createElement("button")
var tx = document.createTextNode("X");
btn.onclick = function() {
$(this).closest(".box").remove()
}
btn.appendChild(tx);
mainDiv.appendChild(btn)
document.getElementById('gallery').appendChild(mainDiv)
}
}
function uploadFile(file, i) {
var xhr = new XMLHttpRequest()
var formData = new FormData()
xhr.open('POST', true)
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
// Update progress (can be used to show progress indicator)
xhr.upload.addEventListener("progress", function(e) {
updateProgress(i, (e.loaded * 100.0 / e.total) || 100)
})
xhr.addEventListener('readystatechange', function(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
updateProgress(i, 100) // <- Add this
} else if (xhr.readyState == 4 && xhr.status != 200) {
// Error. Inform the user
}
})
formData.append('upload_preset', 'ujpu6gyk')
formData.append('file', file)
xhr.send(formData)
}
.add-photo {
width: 18%;
background-color: #00a100;
color: #fff;
padding: 11px 13px;
border: 3px solid #00a100;
-webkit-transition: 0.3s ease;
transition: 0.3s ease;
cursor: pointer;
text-align: center;
font-size: 13px;
font-weight: 550;
border-radius: 1px;
margin-left: 41%;
}
* {
box-sizing: border-box;
}
#dialogoverlay {
display: none;
opacity: 0.5;
/*so that user can see through it*/
position: fixed;
top: 0px;
left: 0px;
background: black;
z-index: 10;
height: 100%;
width: 100%;
}
#dialogbox {
display: none;
position: fixed;
background: #ffffff;
border-radius: 1px;
border: 0.5px solid #ccc;
z-index: 10;
left: 25%;
top: 20%;
width: 50%;
height: 400px;
-webkit-animation: fadeEffect 0.3s;
animation: fadeEffect 0.3s;
}
#close-popup {
float: right;
background-color: red;
color: #474747;
font-size: 15px;
}
.header {
position: absolute;
width: 100.2%;
background-color: white;
height: 11%;
top: 5.4%;
left: 50%;
transform: translate(-50%, -50%);
}
.content-centre {
width: 99%;
height: 77%;
margin-left: 3px;
margin-top: 46px;
}
#content-leftside {
width: 65%;
height: 100%;
float: left;
}
.tab {
overflow: hidden;
}
.tab button {
width: 33.3%;
height: 14%;
background-color: #acacac;
float: left;
color: white;
outline: none;
cursor: pointer;
padding: 6px;
transition: 0.3s;
border-right: 1px solid #fff;
}
.tab button:hover {
background-color: #474747;
}
.tab button.active {
background-color: #474747;
}
.tabcontent {
display: none;
padding: 6px 12px;
}
#content-rightside {
width: 35%;
height: 100%;
float: right;
background-color: #ffffff;
border-left: 1px solid #dddddd;
}
#right-topbar {
width: 100%;
height: 9%;
background-color: #474747;
color: #fff;
padding: 5px;
text-align: center;
transition: 0.3s;
}
.footer {
position: absolute;
width: 100.2%;
background-color: #474747;
height: 11%;
bottom: -5.6%;
left: 50%;
/* top: calc(50% - 50px); */
transform: translate(-50%, -50%);
}
/*------------------- UPLOAD AREA -----------------------*/
#drop-area {
border: 2px dashed #ccc;
border-radius: 8px;
width: 98%;
margin: 24px auto;
padding: 15px;
}
#progress-bar {
display: none;
}
#gallery {
margin-top: 5%;
}
#gallery img {
width: 55px;
height: 50px;
margin-bottom: 10px;
margin-left: 10px
}
.button {
display: inline-block;
padding: 10px;
background: #00a100;
color: #fff;
cursor: pointer;
border-radius: 5px;
}
#fileElem {
display: none;
}
#upload-button {
font-size: 40px;
color: #00a100;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="add-photo" onclick="newAlert.performCustomAlert()">ADD MY PHOTO</button>
<div class="popup-upload">
<div id="dialogoverlay"></div>
<!--------------- SELECT MEDIA BOX ---------------->
<div id="dialogbox">
<!--------------- HEADER OF THE BOX ---------------->
<div class="header">
<!--------------- CLOSE POPUP ---------------->
<button id="close-popup" onclick="newAlert.ok()"><i class="fa fa-times" style="margin-top: 8px; margin-right: 7px;"></i></button>
<div class="select-media">
<i class="fa fa-camera" id="select-camera"></i>
<h2 id="select-media">SELECT YOUR MEDIA</h2>
</div>
</div>
<!--------------- CONTENT OF THE BOX ---------------->
<div class="content-centre">
<!--------------- LEFT CONTENT ---------------->
<div id="content-leftside">
<div class="tab">
<button class="tablinks" id="defaultOpen" onclick="openTab(event, 'Desktop')"><span class="fa fa-desktop"></span> Desktop</button>
<button class="tablinks" onclick="openTab(event, 'Facebook')"><span class="fa fa-facebook"></span> Facebook</button>
<button class="tablinks" onclick="openTab(event, 'Instagram')"><span class="fa fa-instagram"></span> Instagram</button>
</div>
<div id="Desktop" class="tabcontent">
<div id="drop-area">
<form class="my-form">
<span class="fa fa-cloud-upload" id="upload-button"></span>
<p id="drag-text">Drag & Drop Your <br> Photos or Videos <br> To Upload</p>
<input type="file" id="fileElem" multiple accept="image/*" onchange="handleFiles(this.files)">
<label class="button" for="fileElem">or Select Files</label>
</form>
</div>
</div>
<div id="Facebook" class="tabcontent">
<h3>Facebook</h3>
</div>
<div id="Instagram" class="tabcontent">
<h3>Instagram</h3>
</div>
</div>
<!--------------- RIGHT CONTENT ---------------->
<div id="content-rightside">
<!--------------- RIGHT TOPBAR ---------------->
<div id="right-topbar">
<h1>Selected Media</h1>
</div>
<progress id="progress-bar" max=100 value=0></progress>
<div id="gallery" /></div>
</div>
</div>
<div class="footer">
</div>
</div>
</div>
</div>
just replace previewFile function with this.
function previewFile(file) {
let reader = new FileReader()
reader.readAsDataURL(file);
reader.onloadend = function() {
var gallleryDiv=document.getElementById('gallery');
var wrapperDiv = document.createElement("div");
let img = document.createElement('img');
img.src = reader.result;
wrapperDiv.className = "wrapperDiv";
wrapperDiv.appendChild(img)
var textbx = document.createElement("textarea");
wrapperDiv.appendChild(textbx);
var btn = document.createElement("button");
var tx = document.createTextNode("X");
btn.onclick = function() {$(this).closest(".wrapperDiv").remove()}
btn.appendChild(tx);
wrapperDiv.appendChild(btn);
gallleryDiv.appendChild(wrapperDiv);
}
}

Categories

Resources