how do I reload div with countdown - javascript

I have countdown in my container div but when I tried to reload that specific container its reload perfectly but my countdown didn't showed up and also button got disabled..
function refreshDiv() {
$('#container3').load(window.location.href + " #container3");
}
JavaScript
var spn = document.getElementById("count");
var btn = document.getElementById("btnCounter");
var count = 2; // Set count
var timer = null; // For referencing the timer
(function countDown() {
// Display counter and start counting down
spn.textContent = count;
// Run the function again every second if the count is not zero
if (count !== 0) {
timer = setTimeout(countDown, 1000);
count--; // decrease the timer
} else {
// Enable the button
btn.removeAttribute("disabled");
}
}());
this is my html code its work properly when I refresh the whole page but when I refresh #container3 my button got disabled and countdown didn't showed
<div class="container">
<div class="container1">
<h2>choose product </h2>
<input type="file" name="inpFile" id="inpFile">
<div class="image-preview" id="imagePreview">
<img src="" alt="Image Preview" id="zoom" class="image-
preview__image">
<span class="image-preview__default-text">choose image</span>
</div>
</div>
<div class="container2" id="container3">
<h4 id="title">here</h4>
<div class="controls">
<div class="main-controls">
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown" id="btnCounter" disabled>File <span id="count"></span></button>
<div class="dropdown-menu">
<button id="txt-btn" class="dropdown-item" onclick="refreshDiv();">Save</button>

function refreshDiv() {
count = 2;
timer = null;
countDown();
}
I removed the jquery that reloads #container3 and reset your count and timer and it worked for me in a node.js http-server environment... The component refreshes on clicking save.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="container1">
<h2>choose product </h2>
<input type="file" name="inpFile" id="inpFile">
<div class="image-preview" id="imagePreview">
<img src="" alt="Image Preview" id="zoom" class="image-
preview__image">
<span class="image-preview__default-text">choose image</span>
</div>
</div>
<div class="container2" id="container3">
<h4 id="title">here</h4>
<div class="controls">
<div class="main-controls">
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown" id="btnCounter" disabled>File <span id="count"></span></button>
<div class="dropdown-menu">
<button id="txt-btn" class="dropdown-item" onclick="refreshDiv();">Save</button>
<script>
var spn = document.getElementById("count");
var btn = document.getElementById("btnCounter");
var count = 2; // Set count
var timer = null; // For referencing the timer
function countDown() {
// Display counter and start counting down
spn.textContent = count;
// Run the function again every second if the count is not zero
if (count !== 0) {
console.log(count);
timer = setTimeout(countDown, 1000);
count--; // decrease the timer
} else {
// Enable the button
btn.removeAttribute("disabled");
}
};
function refreshDiv() {
count = 2;
timer = null;
countDown();
}
countDown();
</script>
</body>
</html>

Related

Automate a slider with pause and resume functions

I have a slider and I would like to automate it with pause and resume functions. I found this great snippet of code that allows me to pause and resume, however, it only allows me to pause once.
I am struggling to figure out how to make it so the user can pause as many times as they like.
here is the complete code:
$s = 1000; // slide transition speed (for sliding carousel)
$d = 5000; // duration per slide
$w = $('.slide').width(); // slide width
function IntervalTimer(callback, interval) {
var timerId, startTime, remaining = 0;
var state = 0; // 0 = idle, 1 = running, 2 = paused, 3= resumed
this.pause = function () {
if (state != 1) return;
remaining = interval - (new Date() - startTime);
window.clearInterval(timerId);
state = 2;
$('.timer').stop(true, false)
};
this.resume = function () {
if (state != 2) return;
state = 3;
window.setTimeout(this.timeoutCallback, remaining);
$('.timer').animate({"width":$w}, remaining);
$('.timer').animate({"width":0}, 0);
};
this.timeoutCallback = function () {
if (state != 3) return;
callback();
startTime = new Date();
timerId = window.setInterval(callback, interval);
state = 1;
};
startTime = new Date();
timerId = window.setInterval(callback, interval);
state = 1;
}
var starttimer = new IntervalTimer(function () {
autoSlider()
}, $d);
timer();
$('.slider-content').hover(function(ev){
starttimer.pause()
}, function(ev){
starttimer.resume()
});
function timer() {
$('.timer').animate({"width":$w}, $d);
$('.timer').animate({"width":0}, 0);
}
Any help is greatly appreciated.
UPDATE:
Here is the HTML
<div class="slider-content">
<div class="timer"></div>
<div class="slide 1">
<div class="hero-container">
<div class="header-content-container">
<h1 class="entry-title"></h1>
<hr>
<div class="flex-container">
<div class="col1"></div>
<div class="col2"></div>
</div>
<div class="post-link"></div>
</div>
</div>
</div>
<div class="slide 2">
<div class="hero-container">
<div class="header-content-container">
<h1 class="entry-title"></h1>
<hr>
<div class="flex-container">
<div class="col1"></div>
<div class="col2"></div>
</div>
<div class="post-link"></div>
</div>
</div>
</div>
<div class="slide 3">
<div class="hero-container">
<div class="header-content-container">
<h1 class="entry-title"></h1>
<hr>
<div class="flex-container">
<div class="col1"></div>
<div class="col2"></div>
</div>
<div class="post-link"></div>
</div>
</div>
</div>
<div class="slide 4">
<div class="hero-container">
<div class="header-content-container">
<h1 class="entry-title"></h1>
<hr>
<div class="flex-container">
<div class="col1"></div>
<div class="col2"></div>
</div>
<div class="post-link"></div>
</div>
</div>
</div>
</div>

How to create a proper start button on typing game using vanilla javascript

I'm trying to create a start button for my Javascript game that starts the and when the game is over resets the game. As of right now, the button I have starts the game but when it's "Game Over" the timer doesn't reset or start. The words change but not the timer or score. I tried using the reload.location and it didn't do anything.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/css/bootstrap.min.css"> -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css">
<title>One Piece WordBeater</title>
</head>
<body>
<body class="bg-dark text-white">
<header class="bg-secondary text-center p-3 mb-5">
<h1>One Piece Word Beater</h1>
</header>
<div class="container text-center">
<!--Word & Input-->
<div class="row">
<div class="col-md-3 mx-auto">
<p class="lead">Current Level: <span class="text-info" id="levels"></span></p>
</div>
<div class="col-md-6 mx-auto">
<p class="lead">Type the Given Word Within <span class="text-success" id="seconds">5</span> Seconds. </p>
<h2 class="display-2 mb-5" id="current-word">luffy</h2>
<input type="text" class="form-control form-control-lg" placeholder="Start Typing..." id="word-input" autofocus>
<h4 class="mt-3" id="message"></h4>
<br>
<div class="btn-group">
<button type="button" class="btn btn-warning mr-5" id="start"><b>Let's Play!</b></button>
<button type="button" class="btn btn-danger" id="reset"><b>Reset Game</b></button>
</div>
</div>
<div class="col-md-3 mx-auto">
<p class="lead">High Score: <span class="text-info" id="highsocre"></span></p>
</div>
</div>
<!--Time and Columns-->
<div class="row mt-5">
<div class="col md-6">
<h3>Time left: <span id="time">0</span></h3>
</div>
<div class="col md-6">
<h3>Score: <span id="score"> 0 </span></h3>
</div>
</div>
<!--Instructions-->
<div class="row mt-5">
<div class="col md-12">
<div class="card card-body bg-secondary text-white">
<h5>Instructions</h5>
<p>Type each word in the given amount of seconds to score. To play again, just type the current word. Your score
will reset</p>
</div>
</div>
</div>
<!--Level Selector-->
<div class = "row mt-5">
<div class="col md-12">
<div class="card card-body bg-secondary text-white">
<h5>Select the Difficulty</h5>
<div class="row mt-5">
<div class="col md-12">
<div class="btn-group">
<button type="button" class="btn btn-success mr-2" id="easy">Easy</button>
<button type="button" class="btn btn-primary mr-2" id="medium">Medium</button>
<button type="button" class="btn btn-danger" id="hard">Hard</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/js/bootstrap.min.js"></script>
<script src="index.js"></script>
</body>
</html>
JavaScript:
window.addEventListener('load', init,);
//Avaible levels
const levels = {
easy: 5,
medium: 3,
hard: 2,
}
//to cchange level
const currentLevel = levels.easy;
let time = currentLevel;
let score = 0;
let isPLaying;//initalzies game...true if game is on false if game is off
/*function resetGame(){
const resetBtn = document.getElementById('reset')
resetBtn.onclick = function() {
let time = currentLevel;
let score = 0;
let isPLaying; //Show number of seconds
}
}*/
//DOM Elements
const wordInput = document.querySelector('#word-input');
const currentWord = document.querySelector('#current-word');
const scoreDisplay = document.querySelector('#score');
const timeDisplay = document.querySelector('#time');
const message = document.querySelector('#message');
const seconds = document.querySelector('#seconds');
const levelDisplay = document.querySelector('#levels');
const words = [
'luffy',
'zoro',
'shanks',
'nami',
'brook',
'chooper',
'sanji',
'franky',
'jinbe',
'carrot',
'pekoms',
'ace',
'sabo',
'robin',
'bellamy',
'crocodile',
'merry',
'yonko',
'camie',
'nefertari',
'raizo',
'momo',
'law',
'dracule',
'boa',
'buggy',
'golroger',
'bigmom',
'smoker',
'kaido'
];
//initialize Game
/*function init() {
// //Show number of seconds
seconds.innerHTML = currentLevel;
// //load a word from array
showWord(words);
// //Start Matching on word input
wordInput.addEventListener('input', startMatch);
// //Call countdown every second
setInterval(countdown, 1000);
// //Check status
setInterval(checkStatus, 50)
} */
function init() {
//start button
const startBtn = document.getElementById('start')
startBtn.onclick = function() {
//Show number of seconds
seconds.innerHTML = currentLevel;
//load a word from array
showWord(words);
//Start Matching on word input
wordInput.addEventListener('input', startMatch);
//Call countdown every second
setInterval(countdown, 1000);
//Check status
setInterval(checkStatus, 50)
}
}
//level Buttons
//Easy Mode
// document.getElementById('easy').addEventListener('click', easyMode);
// function easyMode(levels) {
// }
//Start Match
//converts words to lowercase
function startMatch() {
if(matchWords()){
isPLaying = true;
time = currentLevel + 1;
showWord(words);
wordInput.value='';
score++;
}
//if score negative -1 display 0
if(score === -1){
scoreDisplay.innerHTML = 0;
}else{
scoreDisplay.innerHTML = score;
}
}
//Match Current Word to word imput
function matchWords(){
if(wordInput.value.toLowerCase() === currentWord.innerHTML) {
message.innerHTML = 'Correct!!!';
return true;
} else {
message.innerHTML = '';
return false;
}
}
//Pick & Show random word
function showWord(words) {
//Generate random array index
const randIndex = Math.floor(Math.random() * words.length);
//Output random word
currentWord.innerHTML = words[randIndex];
}
//Countdown Timer
function countdown() {
//Make sure time is not run out
if(time > 0) {
//Decrease time
time--;
}else if(time === 0) {
//Game Over
isPLaying = false;
}
//Show time
timeDisplay.innerHTML = time;
}
//Check game Status
function checkStatus() {
if(!isPLaying && time === 0){
message.innerHTML = 'Game Over!!';
score = -1;
}
}
Your timer doesn't reset because you didn't stop it with the clearInterval function. The score doesn't reset because you didn't change it in HTML.
First Of all to understang what is wrong with your timer add this code inside your checkStatus() function and open the developer console of your navigator. You will see that your timer continue even if the game is over.
console.log("The game is over but the timer continue...");
OK now, to fix you issue: add this to your code to keep a reference and use it later:
let countDownInterval;
let checkStatusCountDown;
modify your init() function with:
countDownInterval = setInterval(countdown, 1000);
checkStatusCountDown = setInterval(checkStatus, 50);
Now when the game is over we will clear the time interval and reset the score:
function checkStatus() {
if(!isPLaying && time === 0){
message.innerHTML = 'Game Over!!';
score = -1;
scoreDisplay.innerHTML = 0; // reset score in html
clearInterval(checkStatusCountDown); // clear interval
clearInterval(countDownInterval); // clear interval
}
}

How can I make my Slideshow Indicators change their style with my current code?

I have had an issue with placing slideshows in my website. I require more than one slideshow on the same page which has led to multiple problems with the scrolling and such. I finally came across a solution which works almost perfectly however, the indicators do not change color to reflect the current slide.
var w3 = {};
w3.slideshow = function (sel, ms, func) {
var i, ss, x = w3.getElements(sel), l = x.length;
ss = {};
ss.current = 1;
ss.x = x;
ss.ondisplaychange = func;
if (!isNaN(ms) || ms == 0) {
ss.milliseconds = ms;
} else {
ss.milliseconds = 1000;
}
ss.start = function() {
ss.display(ss.current)
if (ss.ondisplaychange) {ss.ondisplaychange();}
if (ss.milliseconds > 0) {
window.clearTimeout(ss.timeout);
ss.timeout = window.setTimeout(ss.next, ss.milliseconds);
}
};
ss.next = function() {
ss.current += 1;
if (ss.current > ss.x.length) {ss.current = 1;}
ss.start();
};
ss.previous = function() {
ss.current -= 1;
if (ss.current < 1) {ss.current = ss.x.length;}
ss.start();
};
ss.display = function (n) {
w3.styleElements(ss.x, "display", "none");
w3.styleElement(ss.x[n - 1], "display", "block");
}
ss.start();
return ss;
};
<html>
<script src="w3.js"></script>
<body>
<div id="2" class="w3-row-padding w3-light-grey w3-padding-64 w3-container">
<div class="w3-content">
<div class="w3-content w3-display-container w3-center">
<div class = "Slide2 w3-animate-opacity">
<h1> Slide Content </h1>
</div>
<!-- Second slide App Development -->
<div class = "Slide2 w3-animate-opacity">
<h1> Slide Content </h1>
</div>
<!-- Third slide App Development -->
<div class = "Slide2 w3-animate-opacity">
<h1> Slide Content </h1>
</div>
<!-- Fourth slide App Development -->
<div class = "Slide2 w3-animate-opacity">
<h1> Slide Content </h1>
</div>
<div class="w3-center w3-container w3-section w3-large w3-text-grey" style="width:100%">
<span class="w3-left w3-hover-text-blue fa fa-arrow-left" onclick="myShow2 .previous()"></span>
<span class="w3-right w3-hover-text-blue fa fa-arrow-right" onclick="myShow2 .next()"></span>
<span class="fa fa-circle demo w3-hover-text-blue w3-transparent" onclick="myShow2 .display(1)"></span>
<span class="fa fa-circle demo w3-hover-text-blue w3-transparent" onclick="myShow2 .display(2)"></span>
<span class="fa fa-circle demo w3-hover-text-blue w3-transparent" onclick="myShow2 .display(3)"></span>
<span class="fa fa-circle demo w3-hover-text-blue w3-transparent" onclick="myShow2 .display(4)"></span>
</div>
</div>
</div>
<script> myShow2 = w3.slideshow(".Slide2", 0); </script>
</div>
</body>
</html>
So the code works well and does what I want except I'm not sure how to make the circle indicators change to blue to reflect the current slide. I have tried completely different approaches except this is the only one that allows multiple slideshows on the same page. Could some please explain to me how I would go about making the circles stay blue when clicked and revert when another is clicked?
I have found a solution to my problem. First I added an extra variable to call a function <script> myShow4 = w3.slideshow(".Slide4", 0, "demo4"); </script>
the "demo4" will be used to find the indicator dots. <span class="fa fa-circle demo4 w3-hover-text-blue w3-transparent" onclick="myShow4 .display(4)"></span>each indicator has the specific class.
`ss.display = function (n) {
ss.current = n;
w3.styleElements(ss.x, "display", "none");
w3.styleElement(ss.x[n - 1], "display", "block");
ss.indicator(demo);
}
ss.indicator = function(n) {
var dots = document.getElementsByClassName(n);
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" w3-text-blue", "");
}
x[ss.current-1].style.display = "block";
dots[ss.current-1].className += " w3-text-blue";
}`
This is the new code in the JS file. on click the display function is called and I edited the function to also call the indicator function which changes the current slide relevant dot to blue while changing the rest to nothing or how they were before. This solution worked for me, adding another function within the called function.

Checkout radial progress bar event

I've created the radial checkout progress bar wit h some animation and transition. Added the event on the button. But the issues is I have the different content for each step in the checkout. What is the best practice. Is it better use the data attr. for this. The content should hide and shown for certain checkout. codepen
<div class="step-1" id="checkout-progress" data-current-step="1">
<div class="progress-bar">
<div class="step step-1 active " data-step="1"><span> 1</span>
<div class="step-check">t</div>
<div class="step-label"> address</div>
</div>
<div class="step step-2" data-step="2"><span> 2</span>
<div class="step-check">a</div>
<div class="step-label"> shipping</div>
</div>
<div class="step step-3" data-step="3"><span> 3</span>
<div class="step-check">b</div>
<div class="step-label"> payment</div>
</div>
<div class="step step-4" data-step="4"><span> 4</span>
<div class="step-check">3</div>
<div class="step-label"> summary</div>
</div>
</div>
</div>
<!-- <div class="button-container">
<div class="btn btn-prev"> previous step</div>
<div class="btn btn-next"> next step</div>
</div> -->
<div class="checkout-content" data-step="1">
<h1>checkout content 1</h1>
<div class="btn btn-next"> next step</div>
<div class="btn btn-next"> next step</div>
</div>
<div class="checkout-content" data-step="2">
<h1>checkout content 2</h1>
<div class="btn btn-next"> next step</div>
<div class="btn btn-next"> next step</div>
</div>
<div class="checkout-content" data-step="3">
<h1>checkout content 3</h1>
<div class="btn btn-next"> next step</div>
<div class="btn btn-next"> next step</div>
</div>
<div class="checkout-content" data-step="4">
<h1>checkout content 4</h1>
<div class="btn btn-next"> next step</div>
<div class="btn btn-next"> next step</div>
</div>
$('.btn-next').on('click', function() {
var currentStepNum = $('#checkout-progress').data('current-step');
var nextStepNum = (currentStepNum + 1);
var currentStep = $('.step.step-' + currentStepNum);
var nextStep = $('.step.step-' + nextStepNum);
var progressBar = $('#checkout-progress');
$('.btn-prev').removeClass('disabled');
if(currentStepNum == 5) {
return false;
}
if(nextStepNum == 5){
$(this).addClass('disabled');
}
// $('.checkout-progress').removeClass('.step-' + currentStepNum).addClass('.step-' + (currentStepNum + 1));
currentStep.removeClass('active').addClass('valid');
currentStep.find('span').addClass('opaque');
currentStep.find('.step-check').removeClass('opaque');
nextStep.addClass('active');
progressBar.removeAttr('class').addClass('step-' + nextStepNum).data('current-step', nextStepNum);
});
$('.btn-prev').on('click', function() {
var currentStepNum = $('#checkout-progress').data('current-step');
var prevStepNum = (currentStepNum - 1);
var currentStep = $('.step.step-' + currentStepNum);
var prevStep = $('.step.step-' + prevStepNum);
var progressBar = $('#checkout-progress');
$('.btn-next').removeClass('disabled');
if(currentStepNum == 1) {
return false;
}
if(prevStepNum == 1){
$(this).addClass('disabled');
}
// $('.checkout-progress').removeClass('.step-' + currentStepNum).addClass('.step-' + (prevStepNum));
currentStep.removeClass('active');
prevStep.find('span').removeClass('opaque');
prevStep.find('.step-check').addClass('opaque');
prevStep.addClass('active').removeClass('valid');
progressBar.removeAttr('class').addClass('step-' + prevStepNum).data('current-step', prevStepNum);
});
Why are you repeating Actions(next & pev) buttons in Contain section in every stage. Make it new section called .actions then you can place your actions buttons their...
Then you can have data-target attribute which holds the value of stepNumber to which it need to go when it clicked...
And you need to change data-target attribute every time when it clicks to which you want user to move next... And also same with pev button...

Showing and hiding div tags by their ID order using a button

I made a small questionnaire and I placed each question in a div tag. I'm trying to display the div tags in order, so when the user click the "Next" button it will move on to the next div and hide the previous one. Kind of like a paging system? I thought about creating some sort of a for loop but I feel like my code is super messy. Any suggestions? Thanks in advance.
<form>
<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<div id="4"></div>
<div id="5"></div>
<div id="6"></div>
<div id="7"></div>
<div id="8"></div>
<div id="9"></div>
<div id="10"></div>
<button type="button">Next</button>
<button type="button">Back</button>
</form>
<script>
visible(){
document.getElementById('1').style.display = "block";
document.getElementById('2').style.display = "none";
document.getElementById('3').style.display = "none";
document.getElementById('4').style.display = "none";
document.getElementById('5').style.display = "none";
document.getElementById('6').style.display = "none";
document.getElementById('7').style.display = "none";
document.getElementById('8').style.display = "none";
document.getElementById('9').style.display = "none";
document.getElementById('10').style.display = "none";
}
You can use javascript functions to setup your divs. This uses jQuery for smooth transition as well.
<div id="1">Question 1</div>
<div id="2" class="hidden">Question 2</div>
<div id="3" class="hidden">Question 3</div>
<div id="4" class="hidden">Question 4</div>
<div id="5" class="hidden">Question 5</div>
<div id="6" class="hidden">Question 6</div>
<div id="7" class="hidden">Question 7</div>
<div id="8" class="hidden">Question 8</div>
<div id="9" class="hidden">Question 9</div>
<div id="10" class="hidden">Question 10</div>
<button type="button" onclick="reverseDiv();">Back</button>
<button type="button" onclick="advanceDiv();">Next</button>
<script>
var divNum=1;
advanceDiv = function() {
if(divNum < 10) {
divNum++;
$('#' + (divNum-1)).slideToggle();
$('#' + divNum).slideToggle();
}
else {
/* last slide reached */
alert('last question');
}
}
reverseDiv = function() {
if(divNum > 1) {
divNum--;
$('#' + (divNum+1)).slideToggle();
$('#' + divNum).slideToggle();
}
else {
alert('first question');
}
}
</script>
Here's a jsfiddle to show functionality (and also includes arrow keys to move between functions): https://jsfiddle.net/79xupebb/1/
To think about the start and the end in this is case is important.
What happens if you are at the end and then click the next button? Then you have to go to the start. And if you are at the start point and click the previous button, you have to go to the end:
if(current === start && direction === "prev") current = end;
if(current === end && direction === "next") current = start;
To make all the divs display: none and only the first one display: block use CSS, like:
#container div {
display: none;
}
#container div:first-child {
display: block;
}
with HTML
<div id="container">
<div id="1">div1</div>
<div id="2">div2</div>
<div id="3">div3</div>
...
</div>
All togehter with plain JavaScript:
var prev = document.getElementById("prev");
var next = document.getElementById("next");
var start = 1;
var end = 10;
var current = 1;
function slide(direction, start, end) {
document.getElementById(current).style.display = "none";
if(current === start && direction === "prev") {
current = end;
} else if(current === end && direction === "next") {
current = start;
} else if(direction === "next") {
current += 1;
} else if(direction === "prev") {
current -= 1;
}
document.getElementById(current).style.display = "block";
}
prev.addEventListener("click", function() {
slide("prev", start, end);
});
next.addEventListener("click", function() {
slide("next", start, end);
});
#container div {
display: none;
}
#container div:first-child {
display: block;
}
<div id="container">
<div id="1">div1</div>
<div id="2">div2</div>
<div id="3">div3</div>
<div id="4">div4</div>
<div id="5">div5</div>
<div id="6">div6</div>
<div id="7">div7</div>
<div id="8">div8</div>
<div id="9">div9</div>
<div id="10">div10</div>
<button id="prev" type="button">Previous</button>
<button id="next" type="button">Next</button>
</div>
There is a simple way to do what you want. Use a counter (current), start it at 1 and increase it/ decrease it whenever the user clicks one of the buttons, then loop through your div list and make them all display:none except the one that corresponds to your current value.
var current = 1;
function next(){
current+=1;
for(var i = 1; i<10; i++){
document.getElementById(i).style.display = ((current==i)?"block":"none");
}
}
function back(){
current-=1;
for(var i = 1; i<=10; i++){
document.getElementById(i).style.display = ((current==i)?"block":"none");
}
}
<form>
<div id="1" style="display:block">one</div>
<div id="2" style="display:none">two</div>
<div id="3" style="display:none">three</div>
<div id="4" style="display:none">four</div>
<div id="5" style="display:none">five</div>
<div id="6" style="display:none">six</div>
<div id="7" style="display:none">aaaa</div>
<div id="8" style="display:none">bbb</div>
<div id="9" style="display:none">nnn</div>
<div id="10" style="display:none">ggg</div>
<button type="button" onclick="next()">Next</button>
<button type="button" onclick="back()">Back</button>
</form>
Note: My code has no safeguards so it will go below 1 and above 10, you can always check with an if statement in each of the buttons' functions.
var i;
for(i=2;i<=10;i++)
document.getElementById(''+i).style.display = "none";
i=1;
document.getElementById('btnNext').onclick = function(){
document.getElementById(''+i).style.display = "none";
i++;
document.getElementById(''+i).style.display = "block";
}
document.getElementById('btnPrev').onclick = function(){
document.getElementById(''+i).style.display = "none";
i--;
document.getElementById(''+i).style.display = "block";
}
<form>
<div id="1">1</div>
<div id="2">2</div>
<div id="3">3</div>
<div id="4">4</div>
<div id="5">5</div>
<div id="6">6</div>
<div id="7">7</div>
<div id="8">8</div>
<div id="9">9</div>
<div id="10">10</div>
<button type="button" id="btnNext">Next</button>
<button type="button" id="btnPrev">Back</button>
</form>
Add the onclick property to your buttons first:
<button type="button" onclick="showNext()">Next</button>
<button type="button" onclick="showPrev()">Back</button>
Then retrieve the divs by adding the class="quest" to every div
var el = document.getElementsByClassName("quest");
function showNext(){
for(var i=0;i<el.length; i++){
if (el[i].style.display == "block"){
el[i].style.display = "none";
if ((i+1)==el.length) i=-1;
el[i+1].style.display = "block";
break;
}
}
}
function showPrev(){
for(var i=0;i<el.length; i++){
if (el[i].style.display == "block"){
el[i].style.display = "none";
if (i==0) i=el.length;
el[i-1].style.display = "block";
break;
}
}
}

Categories