How to add a textarea to the image preview when uploading - javascript

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);
}
}

Related

Serve text instead of images - Trivia javascript game

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>

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.

Get selected value from div dropdown

I have a dropdown from which I want to find the selected value.
The dropdown is basically a big blue button which, when pressed, shows different customers:
When an option is clicked, the value changes to the selected customer.
What I want to do is access this value somewhere else in my HTML script.
var Klanten = [
'niet-declareerbaar',
'ING',
'NNPC',
'Meewind',
];
var Projects = [
'alm',
'risicobeheer',
'RQ',
'overige',
];
var Tarieven = [
'standaard tarief',
'korting (50%)',
'Cadeau',
]
var project = 'overig';
var Tarief = 'standaard tarief';
var startYear = 2000;
var endYear = 2020;
var klant = 0;
var year = 0;
var selectedDays = new Array();
var mousedown = false;
var mousemove = false;
function loadKlanten() {
for (var i = 0; i < Klanten.length; i++) {
var doc = document.createElement('div');
doc.innerHTML = Klanten[i];
doc.classList.add('dropdown-item');
doc.onclick = (function () {
var selectedKlant = i;
return function () {
klant = selectedKlant;
document.getElementById('curKlant').innerHTML = Klanten[klant];
loadCalendarDays();
return klant;
};
})();
document.getElementById('Klanten').appendChild(doc);
}
}
function loadProjects() {
document.getElementById('Projects').innerHTML = '';
for (var i = 0; i < Projects.length; i++) {
var doc = document.createElement('div');
doc.innerHTML = Projects[i];
doc.classList.add('dropdown-item');
doc.onclick = (function () {
var selectedProject = i;
return function () {
project = selectedProject;
document.getElementById('curProject').innerHTML = Projects[project];
loadProjects();
return project;
};
})();
document.getElementById('Projects').appendChild(doc);
}
}
function loadTarief() {
document.getElementById('Tarieven').innerHTML = '';
for (var i = 0; i < Tarieven.length; i++) {
var doc = document.createElement('div');
doc.innerHTML = Tarieven[i];
doc.classList.add('dropdown-item');
doc.onclick = (function () {
var selectedTarief = i;
return function () {
Tarief = selectedTarief;
document.getElementById('curTarief').innerHTML = Tarieven[Tarief];
loadTarief();
return Tarief;
};
})();
document.getElementById('Tarieven').appendChild(doc);
}
}
var start_hour=0;
var end_hour = 10;
var hour = 0;
function loadHours() {
document.getElementById('hours').innerHTML = '';
for (var i = start_hour; i <= end_hour; i++) {
var doc = document.createElement('div');
doc.innerHTML = i;
doc.classList.add('dropdown-item');
doc.onclick = (function () {
var selectedHour = i;
return function () {
hour = selectedHour;
document.getElementById('curHour').innerHTML = hour;
loadHours();
return hour;
};
})();
document.getElementById('hours').appendChild(doc);
}
}
function loadCalendarYears() {
document.getElementById('years').innerHTML = '';
for (var i = startYear; i <= endYear; i++) {
var doc = document.createElement('div');
doc.innerHTML = i;
doc.classList.add('dropdown-item');
doc.onclick = (function () {
var selectedYear = i;
return function () {
year = selectedYear;
document.getElementById('curYear').innerHTML = year;
loadCalendarDays();
return year;
};
})();
document.getElementById('years').appendChild(doc);
}
}
function loadCalendarDays() {
document.getElementById('calendarDays').innerHTML = '';
var tmpDate = new Date(year, month, 0);
var num = daysInMonth(month, year);
var dayofweek = tmpDate.getDay()-1; // find where to start calendar day of week
for (var i = 0; i <= dayofweek; i++) {
var d = document.createElement('div');
d.classList.add('day');
d.classList.add('blank');
document.getElementById('calendarDays').appendChild(d);
}
for (var i = 0; i < num; i++) {
var tmp = i + 1;
var d = document.createElement('div');
d.id = 'calendarday_' + tmp;
d.className = 'day';
d.innerHTML = tmp;
d.dataset.day = tmp;
d.addEventListener('click', function () {
this.classList.toggle('selected');
if (!selectedDays.includes(this.dataset.day))
selectedDays.push(this.dataset.day);
else selectedDays.splice(selectedDays.indexOf(this.dataset.day), 1);
});
d.addEventListener('mousemove', function (e) {
e.preventDefault();
if (mousedown) {
this.classList.add('selected');
if (!selectedDays.includes(this.dataset.day))
selectedDays.push(this.dataset.day);
}
});
d.addEventListener('mousedown', function (e) {
e.preventDefault();
mousedown = true;
});
d.addEventListener('mouseup', function (e) {
e.preventDefault();
mousedown = false;
});
document.getElementById('calendarDays').appendChild(d);
}
var clear = document.createElement('div');
clear.className = 'clear';
document.getElementById('calendarDays').appendChild(clear);
}
function daysInMonth(month, year) {
var d = new Date(year, month + 1, 0);
return d.getDate();
}
window.addEventListener('load', function () {
var date = new Date();
month = date.getMonth();
year = date.getFullYear();
document.getElementById('curKlant').innerHTML = Klanten[klant];
document.getElementById('curTarief').innerHTML = Tarief;
document.getElementById('curHour').innerHTML = hour;
document.getElementById('curProject').innerHTML = project;
loadProjects();
loadKlanten();
loadTarief();
loadCalendarDays();
loadHours();
});
body,
* {
padding: 0px;
margin: 0px;
box-sizing: border-box;
}
.calendar {
background-color: white;
padding: 20px;
}
.calendar .dropdown {
display: none;
position: absolute;
background-color: #fff;
color: #0047bA;
text-align: center;
font-size: 14pt;
padding-top: 5px;
padding-bottom: 5px;
padding-left: 30px;
padding-right: 30px;
width: 160px;
left: 0px;
z-index: 2000;
}
.calendar .dropdown .dropdown-item {
cursor: pointer;
opacity: 0.7;
transition: 0.5s opacity;
}
.calendar .dropdown .dropdown-item:hover {
opacity: 1;
}
.calendar .hours{
display: none;
}
.calendar .tarief {
display: none;
}
.calendar .title {
text-align: center;
font-size: 20pt;
}
.calendar .calendar-btn {
float: left;
background-color: #0047bA;
color: white;
text-align: center;
font-size: 14pt;
padding-top: 5px;
padding-bottom: 5px;
position: relative;
width: 20%;
cursor: pointer;
transition: 0.5s background-color;
}
.calendar .month-btn {
width: 40%;
height: 55px;
}
.calendar .project-btn {
height: 55px;
}
.calendar .calendar-btn:hover {
background-color: #1f71a1;
}
.calendar .hours-btn{
float: middle;
height: 55px;
}
.calendar .tarief-btn {
float: left;
height: 55px;
}
.calendar .calendar-dates .days .day {
float: left;
width: 12%;
margin: 1%;
padding: 1%;
font-size: 13pt;
text-align: center;
border-radius: 10px;
border: solid 1px #ddd;
}
.calendar .calendar-dates .days .day.blank {
background-color: white;
border: none;
}
.calendar .calendar-dates .days .day.selected {
background-color: #0047bA;
color: white;
cursor: pointer;
opacity: 0.9;
transition: 0.1s opacity;
}
.calendar .calendar-dates .days .day.selected:hover {
opacity: 1;
}
.calendar .calendar-dates .days .day.label {
height: 40px;
background-color: white;
color: black;
border: none;
font-weight: bold;
}
.clear {
clear: both;
}
#media only screen and (max-width: 960px) {
.calendar {
width: 100%;
margin: 0px;
margin: 0px;
box-sizing: border-box;
position: relative;
left: 0px;
}
}
<!DOCTYPE html>
<div>
<html>
<div>
<head>
<!-- CSS property to place div
side by side -->
<style>
#middlebox {
float: left;
width: 65%;
height: 400px;
}
#rightbox {
float: right;
background-color: white;
width: 35%;
height: 450px;
}
h1 {
color: green;
text-align: center;
}
</style>
</head>
<div>
<div id="middlebox">
<body>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta charset="utf-8">
<link href="/static/calendar3.css" rel="stylesheet">
</head>
<body>
<div class="calendar" id="calendar">
<div class="calendar-btn month-btn" onclick="$('#Klanten').toggle('fast')">
<span id="curKlant"></span>
<div id="Klanten" class="months dropdown"></div>
</div>
<div class="calendar-btn project-btn" onclick="$('#Projects').toggle('fast')">
<span id="curProject"></span>
<div id="Projects" class="projects dropdown"></div>
</div>
<div class="calendar-btn hours-btn" onclick="$('#hours').toggle('fast')">
<span id="curHour"></span>
<div id="hours" class="hours dropdown"></div>
</div>
<div class="calendar-btn tarief-btn" onclick="$('#Tarieven').toggle('fast')">
<span id="curTarief"></span>
<div id="Tarieven" class="Tarieven dropdown"></div>
</div>
<div class="clear"></div>
<div class="calendar-dates">
<div class="days">
<div class="day label">MON</div>
<div class="day label">TUE</div>
<div class="day label">WED</div>
<div class="day label">THUR</div>
<div class="day label">FRI</div>
<div class="day label">SAT</div>
<div class="day label">SUN</div>
<div class="clear"></div>
</div>
<div id="calendarDays" class="days">
</div>
</div>
<html>
<head>
<style>
.modal {
display: none;
/* Hidden by default */
position: fixed;
/* Stay in place */
z-index: 1;
/* Sit on top */
left: 0;
top: 0;
width: 100%;
/* Full width */
height: 100%;
/* Full height */
overflow: auto;
/* Enable scroll if needed */
background-color: rgb(0, 0, 0);
/* Fallback color */
background-color: rgba(0, 0, 0, 0.4);
/* Black w/ opacity */
}
.modal-content {
background-color: #fefefe;
margin: 15% auto;
/* 15% from the top and centered */
padding: 20px;
border: 1px solid #888;
width: 80%;
/* Could be more or less, depending on screen size */
}
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
</style>
</head>
<body>
<style>
.myBtn {
border: none;
color: white;
padding: 16px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 14px;
margin: 4px 2px;
transition-duration: 0.2s;
cursor: pointer;
}
.myBtn1 {
background-color: white;
color: black;
border: 2px solid #0047bA;
}
.myBtn1:hover {
background-color: #0047bA;
color: white;
}
</style>
<button id="myBtn" class="myBtn myBtn1">Uren indienen</button>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Je staat op het punt om je uren in te dienen, weet je zeker dat alles klopt?</p>
<html>
<head>
<style>
.button {
border: none;
color: white;
padding: 16px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 14px;
margin: 4px 2px;
transition-duration: 0.2s;
cursor: pointer;
}
.button1 {
background-color: white;
color: black;
border: 2px solid #0047bA;
}
.button1:hover {
background-color: #0047bA;
color: white;
}
</style>
</head>
<body>
<a href="{{ url_for('schrijven') }}">
<button class="button button1">Ja, dien mijn uren in</button></a>
</body>
</div>
</div>
<script>
var modal = document.getElementById("myModal");
var btn = document.getElementById("myBtn");
var span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
</body>
</html>
</div>
<script type="text/javascript" src="/static/jscodes/jquery-3.5.1.min.js"></script>
<script type="text/javascript" src="/static/jscodes/calendar3.js" async></script>
</body>
</div>
<div class="card">
<div class="rightbox_buttons" id="rightbox">
<div>
<h2>Welke uren heb ik geschreven?</h2>
</div>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {font-family: Arial;}
/* Style the tab */
.tab {
overflow: hidden;
border: 1px solid #ccc;
background-color: #f1f1f1;
}
/* Style the buttons inside the tab */
.tab button {
background-color: inherit;
float: left;
border: none;
outline: none;
cursor: pointer;
padding: 14px 16px;
transition: 0.3s;
font-size: 17px;
}
/* Change background color of buttons on hover */
.tab button:hover {
background-color: #ddd;
}
/* Create an active/current tablink class */
.tab button.active {
background-color: #ccc;
}
/* Style the tab content */
.tabcontent {
display: none;
padding: 6px 12px;
border: 1px solid #ccc;
border-top: none;
}
</style>
</head>
<body>
<div class="tab">
<button class="tablinks" onclick="openCity(event, 'week')">Per week</button>
<button class="tablinks" onclick="openCity(event, 'maand')">Per maand</button>
<button class="tablinks" onclick="openCity(event, 'klant')">Per klant</button>
</div>
<div id="week" class="tabcontent">
<p>Je hebt deze week geschreven: </p>
</div>
<div id="maand" class="tabcontent">
<p>Je hebt deze maand geschreven:</p>
</div>
<div id="klant" class="tabcontent">
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Get Selected Option Value</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function(){
$("select.klant").change(function(){
var selectedCountry = $(this).children("option:selected").val();
alert("You have selected the country - " + selectedCountry);
});
});
</script>
</head>
<body>
<form>
<label>kies klant:</label>
<select class="klant">
{% for klant in klant %}
<option value="{{ klant }}" SELECTED>{{ klant }}</option>
{% endfor %}
</select>
<input type="text" size="30" name="display" id="display" />
</form>
</body>
</html>
</div>
<script>
function openCity(evt, cityName) {
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(cityName).style.display = "block";
evt.currentTarget.className += " active";
}
</script>
</body>
</html>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
{%endblock%}
Preferably, I want to save the selected customer in a new variable (so I can return it in my HTML) and use it later on. How would I be able to do this?
You to put the below code to save the selected value inside a variable inside the onclick event.
var selected_Value= $('.dropdownid :selected').val();

EventListener Click does not working on H tag inside

I have this simple Modal that's shows up upon clicking button and a Page inside it, depends of which button is click,
uno is for page1, dos is for page2 tres is for page3.
the whole box is a button and i have h3 inside it(It's for the title of that button), but when i click the green area which is H3 my pages does not shos up.
I know the problem is that when it clicks h3 it targets the h3 and h3 has ni ID in it.
Can someone help me to make my h3 act as div when i click it?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.myBtn {
width: 100px;
height: 100px;
background-color: aqua;
margin: 10px;
text-align: center;
}
.myBtn h3 {
background-color:green;
line-height: 2;
cursor: pointer;
}
.myBtn:hover {
background-color: aquamarine;;
}
.btns {
float: left;
}
.modal {
display: none;
background-color: aqua;
float: right;
width: 400px;
height: 600px;
}
.page1 {
position: absolute;
display: none;
background-color: burlywood;
margin: 20px;
width: 300px;
height: 150px;
}
.p1 {
border: 2px solid red;
}
.p2 {
border: 2px solid blue;
}
.p3 {
border: 2px solid green;
}
</style>
</head>
<body>
<p>Click the button to Show Modal.</p>
<div class="btns">
<div class="myBtn" id="uno">
<h3>uno</h3>
</div>
<div class="myBtn " id="dos">
<h3>dos</h3>
</div>
<div class="myBtn "id="tres">
<h3>tres</h3></div>
</div>
<div class="modal">
Modal
<div class="page1 p1">Page1</div>
<div class="page1 p2">Page2</div>
<div class="page1 p3">Page3</div>
</div>
<!--JS-->
<script>
var btn = document.querySelectorAll('.myBtn');
var getModal = document.querySelector('.modal');
var getPages = document.querySelectorAll('.page1');
//console.log(getPages);
for(let i=0; i<btn.length;i++ ){
btn[i].addEventListener('click', () => {
hideModal();
getId();
displayPage()});
}
function hideModal(){
getModal.style.display = "block";
}
function getId(){
//console.log(event.target.id);
}
function hideall(){
for(let i=0; i<getPages.length;i++ ){
getPages[i].style.display = 'none';
}
}
function displayPage(){
hideall();
var btnId = event.target.id;
console.log(btnId);
if(btnId == "uno"){
getPages[0].style.display = "block";
}else if(btnId == "dos"){
getPages[1].style.display = "block";
}else if(btnId == "tres"){
getPages[2].style.display = "block";
}
console.log(getPages[0]);
}
window.addEventListener('click', closeIfOutside);
function closeIfOutside(e) {
if(e.target == getModal)
{
getModal.style.display = 'none';
}
}
</script>
</body>
</html>
<html>
You can add pointer-events: none to your h3 elements so that any clicks will fall through to the containing parent div behind it, allowing you to get the correct id to show the correct page:
.myBtn h3 {
background-color: green;
line-height: 2;
cursor: pointer;
pointer-events: none;
}
See example below:
var btn = document.querySelectorAll('.myBtn');
var getModal = document.querySelector('.modal');
var getPages = document.querySelectorAll('.page1');
//console.log(getPages);
for (let i = 0; i < btn.length; i++) {
btn[i].addEventListener('click', () => {
hideModal();
getId();
displayPage()
});
}
function hideModal() {
getModal.style.display = "block";
}
function getId() {
//console.log(event.target.id);
}
function hideall() {
for (let i = 0; i < getPages.length; i++) {
getPages[i].style.display = 'none';
}
}
function displayPage() {
hideall();
var btnId = event.target.id;
//console.log(btnId);
if (btnId == "uno") {
getPages[0].style.display = "block";
} else if (btnId == "dos") {
getPages[1].style.display = "block";
} else if (btnId == "tres") {
getPages[2].style.display = "block";
}
//console.log(getPages[0]);
}
window.addEventListener('click', closeIfOutside);
function closeIfOutside(e) {
if (e.target == getModal) {
getModal.style.display = 'none';
}
}
.myBtn {
width: 100px;
height: 100px;
background-color: aqua;
margin: 10px;
text-align: center;
}
.myBtn h3 {
background-color: green;
line-height: 2;
cursor: pointer;
pointer-events: none;
}
.myBtn:hover {
background-color: aquamarine;
;
}
.btns {
float: left;
}
.modal {
display: none;
background-color: aqua;
float: right;
width: 400px;
height: 600px;
}
.page1 {
position: absolute;
display: none;
background-color: burlywood;
margin: 20px;
width: 300px;
height: 150px;
}
.p1 {
border: 2px solid red;
}
.p2 {
border: 2px solid blue;
}
.p3 {
border: 2px solid green;
}
<p>Click the button to Show Modal.</p>
<div class="btns">
<div class="myBtn" id="uno">
<h3>uno</h3>
</div>
<div class="myBtn " id="dos">
<h3>dos</h3>
</div>
<div class="myBtn " id="tres">
<h3>tres</h3>
</div>
</div>
<div class="modal">
Modal
<div class="page1 p1">Page1</div>
<div class="page1 p2">Page2</div>
<div class="page1 p3">Page3</div>
</div>

Javascript Slideshow Functions Not Working

I would please like an explanation to why the slideshow is not working. Below I have used an interval to perpetually change the slideshow, if userClick is false. The white and squared buttons (made of divs) are set to call upon two functions; slideRight() or slideLeft() and clicked(). When the buttons are clicked however, the clicked() function does not seem to change the variable, based on the data on top of the page.
<body>
<div class="page-wrapper">
<header>
<div class="headContent">
<h1 class="titleText">Slideshow</h1>
<h2 class="subTitleText">A slideshow made with JavaScript.</h2>
<p>userClick <span id="uc"></span></p>
</div>
<nav>
<ul>
<li>Home</li>
<li>About</li>
<li>Gallery</li>
</ul>
</nav>
</header>
<div class="body-wrapper">
<h1 class="titleText">Slideshow</h1>
<div id="slideshow">
<div id="leftSlide" onclick="leftSlide(); clicked()"></div>
<div id="rightSlide" onclick="rightSlide(); clicked()"></div>
</div>
<p>The image is not invoked by a tag, but invoked by the background property using Javascript.</p>
</div>
<footer>
<p id="footerText">© 2017 <br>Designed by JastineRay</p>
</footer>
</div>
<script language="javascript">
// Slide function
var slide = ["minivan", "lifeinthecity", "sunsetbodyoflove"];
var slideTo = 1;
window.onload = getSlide();
// Previous Image
function leftSlide() {
if (slideTo != 0) {
slideTo = slideTo - 1;
} else if (slideTo == 0) {
slideTo = slide.length - 1;
} else {
alert('SLIDE ERROR');
}
getSlide();
}
// Next Image
function rightSlide() {
if (slideTo != (slide.length - 1)) {
slideTo = slideTo + 1;
} else if (slideTo == (slide.length - 1)) {
slideTo = 0;
} else {
alert('SLIDE ERROR');
}
getSlide();
}
function getSlide() {
imageURL = 'url(images/' + slide[slideTo] + '.jpg)';
document.getElementById("slideshow").style.backgroundImage = imageURL;
}
// Interval Slideshow & Check if user clicked (timeout)
var userClick = false;
window.onload = slideInterval(5000);
// Start Slideshow
function slideInterval(interval) {
while (userClick = false) {
setInterval(function() {
rightSlide();
}, interval)
}
}
// Stop Slideshow and start timeout
function clicked() {
userClick = true;
setTimeout(function() {
userClick = false;
slideInterval();
}, 2000)
}
window.onload = function() {
setInterval(document.getElementById("uc").innerHTML = userClick), 100
}
</script>
</body>
CSS coding below.
* {
margin: 0;
padding: 0;
}
.page-wrapper {
width: 100%;
}
// Class Styling
.titleText {
font-family: monospace;
font-size: 40px;
}
.subTitleText {
font-family: monospace;
font-size: 20px;
font-weight: normal;
}
// Header Styling
header {
height: 500px;
}
.headContent {
margin: 30px 7%;
}
// Navigation Styling
nav {
overflow: hidden;
}
nav ul {
background: black;
background: linear-gradient(#595959, black);
list-style-type: none;
font-size: 0;
padding-left: 13.33%;
margin: 40px 0;
}
nav ul li {
padding: 15px 20px;
border-right: 1px solid #595959;
border-left: 1px solid #595959;
color: white;
display: inline-block;
font-size: 20px;
font-family: sans-serif;
}
// Body Styling
.body-wrapper {
}
.body-wrapper > .titleText {
text-align: center;
font-size: 50px;
}
#slideshow {
overflow: hidden;
margin: 20px auto;
border: 2px solid blue;
height: 350px;
max-width: 800px;
background-size: cover;
background-position: center;
position: relative;
}
#leftSlide {
position: absolute;
left: 40px;
top: 175px;
background-color: white;
height: 40px;
width: 40px;
}
#rightSlide {
position: absolute;
left: 100px;
top: 175px;
background-color: white;
height: 40px;
width: 40px;
}
// Footer Styling
Try changing the checking part to:
window.onload = function() {
setInterval(function () {
document.getElementById("uc").innerHTML = userClick;
}, 100);
}
The first argument of setInterval has to be a function (something that can be called), not a generic piece of code.

Categories

Resources