Creating a next and previous button with simple JavaScript? If statement? - javascript

So I'm trying to do a simple back forward with a picture slider. I have gotten the next on the button, but need to create the function for back.
I cannot seem to get it and cannot remember with simple pure javascript. What would the if statement be? I assume the position needs to be changed to 0. Thank you for the advice.
For the forward I have:
function Forward()
xxxx[arrayPosition].className = "thumb";
mm[arrayPosition].className = "yyy";
if(arrayPosition == xxxx.length - 1){
arrayPosition = 0; }
else{
arrayPosition = arrayPosition + 1; in memory }
xxxx[arrayPosition].className = "thumb active";
mm[arrayPosition].className = "yyy active"; }

When going back, you would want to check if the current arrayPosition is 0. If so, the array position should be updated to be the last index. For example:
if(arrayPosition === 0) {
arrayPosition = xxxx.length - 1;
} else {
arrayPosition -= 1;
}

try this
function Forward(){
xxxx[arrayPosition].className = "thumb";
mm[arrayPosition].className = "yyy";
if((arrayPosition == xxxx.length - 1)||
(arrayPosition == 0)){
arrayPosition = 0;
}else{
arrayPosition = arrayPosition + 1;
}
xxxx[arrayPosition].className = "thumb active";
mm[arrayPosition].className = "yyy active";
}

Related

Issue linking images to dynamically created jquery elements

So, I'm very new, so apologies if this is a silly question. I have worked out a Trivia Quiz for my learning to code classes I'm taking. I want to display an image on the confirmation screen that shows whether the user was right or wrong. I think the code is correct-ish? I'm not sure what isn't working.
I left out the main Question and answer object for space. Sorry if I didn't format this ideally? I'm still kinda figuring out how things work here.
Here is my code for reference:
//array to help me iterate and insert images
var imgArray = ["question1", "question2", "question3", "question4", "question5", "question6", "question7", "question8", "question9", "question10", "question11", "question12", "question13"];
var currentQuestion = 0;
var win = 0;
var lose = 0;
var unanswered = 0;
var time = 30;
//set up divs to contain our info
var rightDiv = $("<div class='rightAns'></div>");
var timerDiv = $("<div class='countdown'><h3></h3></div>");
var questionDiv = $("<div class='question'><h1></h1></div><br>");
var answerDiv = $("<div class='answers'></div>");
//object keys to return questions in order
var keys = Object.keys(questions);
var key = keys[n];
var n = 0;
//function to setup and restart game
function reset() {
$("#start-button").hide("slow");
$("#start-here").hide("slow");
win = 0;
lose = 0;
unanswered = 0;
n = 0;
key = keys[n];
currentQuestion = 0;
$("#question-block").empty();
var reset = function () {
time = 30;
$(".rightAns").empty();
$(".rightAns").remove();
// $("#image").empty();
$("#time-remaining").append(timerDiv);
$(".countdown h3").html("Time Remaining: " + time);
$("#question-block").append(questionDiv);
$("#question-block").append(answerDiv);
}
reset();
//function to show questions
function showQuestion() {
$(".question h1").html(questions[key].question);
for (var i = 0; i < questions[key].answers.length; i++) {
$(".answers").append("<button class='answer btn btn-danger btn-lg m-1'>" + questions[key].answers[i] + "</button>");
}
$(".answers button").on("click", function () {
var selected = $(this).text();
//if then to check question correctness
if (selected === questions[key].correct) {
clearInterval(counter);
$(timerDiv).remove();
$(questionDiv).remove();
$(".answers button").remove();
$(answerDiv).remove();
$("#correct-answer").append(rightDiv);
$(".rightAns").text("That's Correct!!");
$("#image").html('<img src = ".assets/images/' + imgArray[currentQuestion] + '" width = "400px">');
win++;
currentQuestion++;
} else {
clearInterval(counter);
$(timerDiv).remove();
$(questionDiv).remove();
$(".answers button").remove();
$(answerDiv).remove();
$("#correct-answer").append(rightDiv);
$(".rightAns").text("Nope! The correct answer was: " + questions[key].correct);
$("#image").html('<img src = ".assets/images/' + imgArray[currentQuestion] + '" width = "400px">');
lose++;
currentQuestion++;
}
n++;
key = keys[n];
//checking to see if there are more questions left
if (checkForLast()) {
finalScore();
} else {
setTimeout(countReset, 3 * 1000);
setTimeout(reset, 3 * 1000);
setTimeout(showQuestion, 3 * 1000);
}
});
}
showQuestion();
var counter = setInterval(count, 1000);
//show time remaining for each question
function count() {
time--;
$(".countdown h3").html("Time Remaining: " + time);
if (time < 1) {
clearInterval(counter);
$(timerDiv).remove();
$(questionDiv).remove();
$(".answers button").remove();
$("#correct-answer").append(rightDiv);
$(".rightAns").html("You took too long! The correct answer was: " + questions[key].correct);
unanswered++;
n++;
key = keys[n];
if (checkForLast()) {
finalScore();
} else {
setTimeout(countReset, 3 * 1000);
setTimeout(reset, 3 * 1000);
setTimeout(showQuestion, 3 * 1000);
}
}
}
function checkForLast() {
if (key === undefined) {
return true;
}
return false;
}
//timer for the message after you choose your answer
function countReset() {
counter = setInterval(count, 1000);
}
//showthe final score screen
function finalScore() {
$(".rightAns").remove();
$("#image").empty();
$("#question-block").prepend("<h2>Unanswered: " + unanswered + "</h2>");
$("#question-block").prepend("<h2>Incorrect: " + lose + "</h2>");
$("#question-block").prepend("<h2>Correct: " + win + "</h2>");
$("#start-button").show();
$("#start-here").show();
}
};
//function to start game on button click
$(document).on("click", "#start-button", reset);
});
After tinkering for a bit, I dropped the "." at the beginning of the call and added the .jpg to the section after imgArray[currentQuestion]. That solved it. Thanks for the suggestions.

Javascript Pomodoro Timer - Pause/Play/General Functionality

so I seem to be having some real logic errors amidst my timer here, and I'm not quite sure how to fix them. I've made the code somewhat work, but I know for a fact there's a handful of logical errors, and I honestly have been working on it for a few days intermittently and can't seem to get it solved. Based on the code I've laid out you can pretty much understand my thinking of how I want to tackle this issue. I understand this isn't best practice, but I am just trying to work on my problem solving on these issues! Any help is greatly appreciated. I really need the most help on figuring out how to configure the Pause and Play functions with my given timer functionality. (Please no jQuery examples only raw JS)
// Necessary Variables for the program
let timer = document.querySelector(".time");
let button = document.querySelector("#btn");
let subtractBreak = document.querySelector("#subtractBreak");
let addBreak = document.querySelector("#addBreak");
let subtractSession = document.querySelector("#subtractSesssion");
let addSession= document.querySelector("#addSession");
// Keeping up with the current count of the break and session
let currentCount = document.getElementsByClassName("counterNum");
// Keeps up with all the buttons on session and break +/-
let counterBtn = document.getElementsByClassName("counterBtn");
// Pause and play Variables
let pause = document.querySelector("#pause");
let play = document.querySelector("#play");
// keeps up with an offsetting count.
let count = 0;
let timerGoing = false;
let sessionTimeLeft = 1500;
let breakTimeLeft = 5;
let timeWhilePaused = sessionTimeLeft;
let paused = false;
function formatTimer(time){
let minutes = Math.floor(time / 60);
let seconds = time % 60;
return `${minutes.toLocaleString(undefined, {minimumIntegerDigits: 2})}:${seconds.toLocaleString(undefined, {minimumIntegerDigits: 2})}`;
}
// This function needs to be fixed - It allows the timer to go negative past 0.
function countdown(){
timerGoing = true;
count++;
timer.innerHTML = formatTimer(sessionTimeLeft - count);
// Used to remove the listener
button.removeEventListener("click", interval);
console.log("Timer is at: " + formatTimer(sessionTimeLeft - count) + "\nCount is at: " + count + "\nsessionTimeLeft = " + sessionTimeLeft);
// Checking if the time of the current session is up
if(count == sessionTimeLeft){
timerGoing = false;
alert("We're here stop...");
startBreak(breakTimeLeft);
}
}
button.addEventListener("click", interval);
function interval(e){
setInterval(countdown, 1000);
console.log("running");
e.preventDefault();
}
/*
I look through the event listener to be sure to check and see if any of them have been hit
not just the first one, which is what it would check for.
*/
for(let i = 0; i < counterBtn.length; i++){
counterBtn[i].addEventListener("click", changeCount);
}
/*
This functions whole job is to see which button was clicked using the 'event target'
Once found it can determine if the id is subtract - then it will subtract the next element
founds' amount, due to the structure of the HTML this will always be the number following;
this process works vice versa for the addition, with the number being the element before.
*/
function changeCount(e){
let clickedButtonsId = e.target.id;
if(timerGoing == false){
if(clickedButtonsId === "subtractBreak"){
let currentValue = e.target.nextElementSibling.innerText;
if(currentValue != 1){
currentValue--;
e.target.nextElementSibling.innerText = currentValue;
breakTimeLeft -= 1;
}
} else if(clickedButtonsId === "subtractSession"){
let currentValue = e.target.nextElementSibling.innerText;
if(currentValue != 1){
currentValue--;
e.target.nextElementSibling.innerText = currentValue;
sessionTimeLeft = currentValue * 60;
// Allows the timer to update in real time
timer.innerHTML = formatTimer(sessionTimeLeft);
}
}
else if(clickedButtonsId === "addBreak"){
let currentValue = e.target.previousElementSibling.innerText;
currentValue++;
e.target.previousElementSibling.innerText = currentValue;
breakTimeLeft += 1;
}
else{
let currentValue = e.target.previousElementSibling.innerText;
currentValue++;
e.target.previousElementSibling.innerText = currentValue;
sessionTimeLeft = currentValue * 60;
// Allows the timer to update in real time
timer.innerHTML = formatTimer(sessionTimeLeft);
}
}
}
/* These functions below are not working */
pause.addEventListener("click", pauseTimer);
function pauseTimer(){
timeWhilePaused = sessionTimeLeft;
button.removeEventListener("click", interval);
console.log("calling pause"+paused+"\n");
paused = true;
console.log("paused after: " + paused);
}
play.addEventListener("click", playTimer);
function playTimer(){
console.log("Paused = " + paused);
if(paused == true){
console.log("calling play");
console.log("Paused = " + paused);
sessionTimeLeft = timeWhilePaused;
setInterval(countdown, 1000);
}
}
function startBreak(time){
console.log("Calling this function");
timer.innerHTML = formatTimer(breakTimeLeft - count);
}

My askQuestion() function in Javascript is always marking the answeras wrong

The link to my pen in CodePen - http://codepen.io/PartTimeCoder/pen/WwMxEX?editors=0010
The Javascript is here:
function randomNum(digits) {
return Math.floor(Math.pow(10, digits - 1) + Math.random() * 9 * Math.pow(10, digits - 1));
}
function askQuestion(digits) {
$(".result").html("");
var factor1 = randomNum(digits);
var factor2 = randomNum(digits);
var correctanswer = factor1 * factor2;
var answer = parseInt($(".answer").val(), 10);
console.log(correctanswer);
$(".question").html(factor1 + " × " + factor2);
var score = 0;
//Problem Starts Here
$(".check").click(function() {
if (correctanswer == answer) {
$(".result").html("Correct");
score += 1;
$(".score").html(score);
askQuestion(digits);
} else {
$(".result").html("Wrong");
score -= 1;
$(".score").html(score);
}
});
//Problem Ends Here
}
$(document).ready(function() {
$(".answer").hide();
$(".check").hide();
var digits = 0;
$(".digits-1").click(function() {
digits += 1;
});
$(".digits-2").click(function() {
digits += 2;
});
$(".digits-3").click(function() {
digits += 3;
});
$(".btn").click(function() {
$(".btn").hide();
$(".answer").show();
$(".check").show();
askQuestion(digits);
});
});
In between the comments is where I think the problem is. For example when it asks 4 x 9 and i input 36, it still marks it as wrong. I don't know why this is doing this. At first I though that the inputted information might still be a string so I used parseInt on it and it still didn't work. All help is appreciated. Thanks in advance!
The problem is that you're caching the initial value of the $('.answer') element in your answer variable. When you do $('.answer').val(), it saves what is there at that time, so if the user changes their answer afterwards, it won't be reflected in your variable. What you want to do is something like this:
// Rest of your code above
var answer = $(".answer");
console.log(correctanswer);
$(".question").html(factor1 + " × " + factor2);
var score = 0;
//Problem Starts Here
$(".check").click(function() {
// Don't check what is in the input until you're ready to use the value.
if (correctanswer == parseInt(answer.val(), 10)) {
$(".result").html("Correct");
score += 1;
$(".score").html(score);
askQuestion(digits);
} else {
$(".result").html("Wrong");
score -= 1;
$(".score").html(score);
}
});
The click handler has a reference to the old answer value. You must get the value from the input everytime. Something like this:
$(".check").click(function() {
var answer = parseInt($(".answer").val(), 10);
if (correctanswer == answer) {
$(".result").html("Correct");
score += 1;
$(".score").html(score);
askQuestion(digits);
} else {
$(".result").html("Wrong");
score -= 1;
$(".score").html(score);
}
});

Make a character move upwards on click

I am making a game similar to Flappy Bird. The character is supposed to move upwards when the browser window is clicked, but my code for this does not work. Here are the relevant lines of code:
var dudeYSpeed = 0;
var dudeXSpeed = 0;
var dudeJumping = false;
var jumpSpeed = -3;
if (mouseDown && dudeJumping === false){
dudeJumping = true;
dudeYSpeed = jumpSpeed;
}
else {
translateY += dudeYSpeed;
dudeYSpeed += gravity;
dudeJumping = false;
}
translateX += dudeXSpeed;
You only update translateY and dudeYSpeed if dudeJumping is true. You should update these variables in every frame, no matter what the input was.

Change Image on click (6 Image Loop)

I have 6 images that I want to swap between by clicking on the image but I can't seem to get the code right in order to make it go to the next picture
HTML
<img src="BCover.jpg" id="ImgGallery" onclick="ImgGallery()"/>
JavaScript
var counter = 1;
ImgGallery.onclick = function (){
if (counter == 1){
document.getElementById("ImgGallery").src = "BCover.jpg";
counter++;
}
else if (counter == 2){
document.getElementById("ImgGallery").src = "MechGP.jpg";
counter++;
}
else if (counter == 3){
document.getElementById("ImgGallery").src = "Mech2.jpg";
counter++;
}
else if (counter == 4){
document.getElementById("ImgGallery").src = "Mech3.jpg";
counter++;
}
else if (counter == 5){
document.getElementById("ImgGallery").src = "Mech4.jpg";
counter++;
}
else if (counter == 6){
document.getElementById("ImgGallery").src = "MCA1.png";
counter==1;
}
};
The problem (other than Spencer's comment about == assignment) seems to be that ImgGallery should be the name of a function, not a reference to the element, as it's being called as a function in the onclick attribute of your img element.
I renamed the ImgGallery() function to rotateGallery to eliminate ambiguity with the id of the element.
I also took some liberty to clean up your code a little by using array cycling instead of a switch statement to handle img gallery rotation.
<img src="BCover.jpg" id="ImgGallery" onclick="rotateGallery()"/>
var counter = 0,
gallery = ["BCover.jpg", "MechGP.jpg", "Mech2.jpg", "Mech3.jpg", "Mech4.jpg", "MCA1.png"],
rotateGallery = function () {
document.getElementById("ImgGallery").src = gallery[counter];
counter++;
if (counter >= gallery.length) {
counter = 0;
}
};
This can be DRYed up a bit. You can include all of your images in an array. JavaScript does not have a native cycle method but you can implement it with the following algorithm.
var images = ["BCover.jpg", "MechGP.jpg", "Mech2.jpg", "Mech3.jpg", "Mech4.jpg", "MCA1.png"];
var gallery = document.getElementById("ImgGallery");
var index = 0;
gallery.addEventListener("click", function() {
gallery.src = images[index];
index = (index === images.length - 1) ? 0 : index + 1;
});
I know the last statement inside the click listener may seem weird, but I wanted to write as little code as possible.
ImageGallery isn't a function, which will cause an error.
However, the main error is counter==1;, on the third last line. The == operator is for testing if a value has equal value (not necessarily equal type though), but for assignment, use the normal = operator.
Try this:
//First, create an array of images (so you can support as many images in the gallery as needed, only needing to update this array)
var images = ["BCover.jpg", "MechGP.jpg", "Mech2.jpg", "Mech3.jpg", "Mech4.jpg", "MCA1.png"],
//and a counter to loop through
c = 0;
//this function is triggered when the image is clicked on sending the image element as a parameter
function nextImg(elem){
//if c is less than the array's length - 1, then add 1 to c, otherwise make c equal 0
c = (c != images.length - 1) ? c + 1 : 0;
//actually change the src attribute of the image
elem.src = images[c];
//and just let you know what image you're up to
document.getElementsByTagName('p')[0].innerHTML = 'Image no. '+(c+1)+'. File name of image: '+images[c];
}
/* Make the image visible */
img{
cursor: pointer;
height: 50px;
width: 50px;
}
<img id='ImageGallery' onclick='nextImg(this)' />
<p>Notice the onclick attribute</p>

Categories

Resources