Stuck on trying to resume paused (stopped) function - Pomodoro timer - javascript

First, JSFiddle does not properly display result of my code, so I'll use CodePen, if that's ok.
Well, I'm trying hard to make a Pomodoro timer, but I'm stuck on pause/resume session. I have to be able to stop executing the function on click(and it should display that particular moment on screen, for example 22:22), and on another click it should be resumed. I know that eval() is not desirable, but could someone please help me with completing my awful code (I know it's a mess, but I'm learning JS every day)? To be more precise, I've managed to pause/stop execution, but I need help with resuming it.
Here is the code:
$( document ).ready(function(){
var toggle = true;
var a = document.getElementById("breakvalue");
a.innerHTML = 7;
var b = document.getElementById("sessionvalue");
b.innerHTML = 25;
$("#crcl").html("<h3>Session</h3>" + "</break>" + "<h1 id = numb>" + b.innerHTML + "</h1>");
$("#breakplus").on("click", function(){
$("#breakvalue").html(eval(a.innerHTML)+1);
});
$("#breakminus").on("click", function(){
if (a.innerHTML>=2){
$("#breakvalue").html(eval(a.innerHTML)-1);
}
});
$("#sessionplus").on("click", function(){
$("#sessionvalue").html(eval(b.innerHTML)+1);
$("#crcl").html("<h3>Session</h3>" + "</break>" + "<h1 id = numb>" + b.innerHTML + "</h1>");
});
$("#sessionminus").on("click", function(){
if(b.innerHTML>=2){
$("#sessionvalue").html(eval(b.innerHTML)-1);
$("#crcl").html("<h3>Session</h3>" + "</break>" + "<h1 id = numb>" + b.innerHTML + "</h1>");
}
});
$("#crcl").on("click", function (){
var capture = document.getElementById("crcl");
var inner = capture.innerHTML;
var head = document.getElementById("numb");
var inn = head.innerHTML;
if(toggle&&isNaN(inn)){
inter = setInterval(function(){
console.log(inn);
minutes = eval(inn.slice(0,2));
seconds=eval(inn.slice(3));
console.log(minutes);
console.log(seconds);
if(seconds>=0){
$("#crcl").html("<h3>Session</h3>" + "</break>" + "<h1>" + minutes + ":" + seconds-- + "</h1>");}
if (seconds<0){
seconds=59;
minutes = eval(minutes-1);
$("#crcl").html("<h3>Session</h3>" + "</break>" + "<h1>" + minutes + ":" + seconds-- + "</h1>");}
if(eval(minutes)<0){
$("#crcl").html("<h1>BREAK!!!</h1>");
clearInterval(inter);
}
toggle=false;
}, 1000);
}
if(toggle&&!isNaN(inn)){
var minutes = eval(b.innerHTML-1);
var seconds=59;
inter = setInterval(function(){
if(seconds>=0){
$("#crcl").html("<h3>Session</h3>" + "</break>" + "<h1 id = numb>" + minutes + ":" + seconds-- + "</h1>");
}
if (seconds<0){
seconds=59;
minutes = eval(minutes-1);
$("#crcl").html("<h3>Session</h3>" + "</break>" + "<h1 id = numb>" + minutes + ":" + seconds-- + "</h1>");}
if(eval(minutes)<0){
$("#crcl").html("<h1>BREAK!!!</h1>");
clearInterval(inter);
}
toggle=false;
}, 1000);
}
if (!toggle) {
clearInterval(inter);
console.log(toggle);
toggle=true;
console.log(toggle);
$("#crcl").remove();
$(".center-block").html("<button type=button class= circle btn btn-primary id = crcl>" + inner + "</button>");
}
});
});
h5{
display:inline-block;
}
p{
font-size:30px;
}
.circle
{
width:500px;
height:500px;
border-radius:50%;
font-size:20px;
color:#fff;
line-height:500px;
text-align:center;
background:#000;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class = "container text-center">
<div>
<h1>Pomodoro Clock</h1>
</div>
<div class="container text-center" id = "length">
<h5>BREAK LENGTH</h5>
<h5>SESSION LENGTH</h5>
</div>
<div class="btn-group text-center">
<button type="button" class="btn btn-primary"id = "breakplus">+</button>
<p id = "breakvalue"></p>
<button type="button" class="btn btn-primary"id = "breakminus">-</button>
</div>
<div class="btn-group text-center">
<button type="button" class="btn btn-primary" id = "sessionplus">+</button>
<p id = "sessionvalue"></p>
<button type="button" class="btn btn-primary"id = "sessionminus">-</button>
</div>
<div class="center-block"><button type="button" class=" circle btn btn-primary" id = "crcl"></button></div>
</div>
</body>
This is the link to my Codepen
Ok, here is JSFiddle, too.

Solved. My mistakes were: forgetting h1 IDs on several places, putting minutes and seconds inside an if statement, and - biggest of all - putting stupid extra code inside the function:
$("#crcl").remove();
$(".center-block").html("<button type=button class= circle btn btn-primary id = crcl>" + inner + "</button>");

Related

How can I stop my timer function if the quiz ends before time is up? Javascript

I have everything working as it should, except for me trying a million different things and not being able to get the timer function to stop counting down if the quiz ends before the 60 seconds is up.
//total score var that is defined in local storage and question number var that will be incremented later on
var totalScore = 0,
questionNumber = 0,
i = 0;
// questions object
allQuestions = [{
question: "What do you call a variable with multiple boolean values?",
choices: ["variable", "object", "array", "let"],
correctAnswer: "array"
},
{
question: "A useful tool for debugging during development is_______.",
choices: ["wrench", "Chrome dev tools", "Visual Studio Code", "keyboard"],
correctAnswer: "Chrome dev tools"
},
{
question: "Where will you find most of the answers to the questions you will have in your coding career?",
choices: ["Teachers", "Coworkers", "User manual", "The Internet"],
correctAnswer: "The Internet"
},
{
question: "What should you do when using git before you push a project to the repository?",
choices: ["pull", "bop it", "save it", "close it"],
correctAnswer: "pull"
}
];
var counterValue = 60;
var mainContent = $('#mainContent');
//logic if correct answer is chosen
function correctGuess() {
totalScore ++;
questionNumber ++;
var updatePage = question(questionNumber);
localStorage.setItem("scoreCount", totalScore);
$('#mainContent').html(updatePage);
if(questionNumber < 4){
var updatePage = question(questionNumber);
$('#mainContent').html(updatePage);
}
};
//logic if incorrect answer is chosen
function incorrectGuess() {
counterValue -= 5;
totalScore = 0;
questionNumber ++;
var updatePage = question(questionNumber);
$('#mainContent').html(updatePage);
};
//starting screen
function welcome() {
mainContent.html('<h2>Welcome to the Code Quiz!</h2>' + '<br />' +
'<h5>If you think you have what it takes, go ahead and click the start button to see how you do!</h5>'
+ '<button type="button" class="btn btn-primary" id="startQuizBtn">Start Quiz!</button>');
document.getElementById("startQuizBtn").addEventListener("click", function() {question(i)});
//timer function
document.getElementById("startQuizBtn").addEventListener("click", function() {timer()})
};
function timer() {
var timer = setInterval(function(){
counterValue -= 1;
$("#timer-value").html(counterValue)
if (counterValue <= 0) {
clearInterval(timer)
displayScore()
}
},1000)
}
//loads start page to begin with
window.onload = function () {
this.welcome();
};
//logic to run through questions object
function question(i) {
if (i < 4) {
mainContent.html('<div id="questionDiv">' +
'<h2>Question ' + (i + 1) + '<h2>' +
'<h3>' + allQuestions[i].question + '</h3>' +
'<input type="radio" class="radiobtn" name="questionChoices" value="' + allQuestions[i].choices[0] + '" checked="yes">' + allQuestions[i].choices[0] + '</input>' + '<br />' +
'<input type="radio" class="radiobtn" name="questionChoices" value="' + allQuestions[i].choices[1] + '">' + allQuestions[i].choices[1] + '</input>' + '<br />' +
'<input type="radio" class="radiobtn" name="questionChoices" value="' + allQuestions[i].choices[2] + '">' + allQuestions[i].choices[2] + '</input>' + '<br />' +
'<input type="radio" class="radiobtn" name="questionChoices" value="' + allQuestions[i].choices[3] + '">' + allQuestions[i].choices[3] + '</input>' + '<br />' +
'<button type="button" class="btn btn-primary" id="submitButton">Submit</button>' + '</div>' );
} else {
chooseNextScreen();
};
//submit button at the bottom of the questions
$('#submitButton').on('click', function() {
if($('input:radio[name=questionChoices]:checked').val() === allQuestions[i].correctAnswer && i < 4) {
correctGuess();
} else {
incorrectGuess();
}
});
};
//logic to decide what screen to append next
function chooseNextScreen(){
if (questionNumber < 4) {
question();
} else {
displayScore();
}
};
// end screen of quiz
function displayScore() {
//Text, form and button on end page
$('#mainContent').html('<h2>Well Done!</h2>' + '<h4> You scored ' + totalScore + '!</h4>' + '<h4>Please enter your name for the end screen</h4>' +
'<hr />' + '<form>' + '<input class="form-control" id="initialsBox" type="text" placeholder="Your Name">' + '<button type="button" class="btn btn-primary" id="hiScoreSubmitBtn">Submit</button>' + '</form>');
// Submit button on end screen of quiz
$('#hiScoreSubmitBtn').on('click', function(event) {
localStorage.setItem(initialsBox[0].value, totalScore);
mainContent.html('<h1>' + initialsBox[0].value + ' scored a ' + totalScore + '!' + '</h1>');
});
var initialsBox = $("#initialsBox");
};
//calls function for quiz to run
question(questionNumber);
Here's the HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<title>Code Quiz</title>
<link rel="stylesheet" type="text/css" href="assets/style.css" />
</head>
<body>
<!--Top row heading of title and time left-->
<div class="row">
<div class="col">
<h1 id="code-quiz">Code Quiz!</h1>
</div>
<div class="col">
<h3 id="timer">Time Left: <span id="timer-value"></span></h3>
</div>
</div>
<!--Main Content-->
<div class="container">
<div id="headingLine" class="row main-heading">
<div class="classname" id="id"></div>
</div>
<div class="row">
<div class="col" id="mainContent">
</div>
</div>
</div>
<!--Script Tags-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<script src="assets/script.js"></script>
</body>
</html>
I cant help but feel like the answer is right in front of me, but I've been staring at it for hours at this point.
document.getElementById("startQuizBtn").addEventListener("click", ()=>{
var counterVal = 5;
timer=setInterval(function() {
counterVal=counterVal-1;
console.log(counterVal)
if(counterVal==0){
clearInterval(timer)
}
},1000)
})

Field updates for a second then disapears

so i made a field status as p paragraph, and it supposed to be able to hold a value after button click but it only appears momentary and disappears
the library js just has the array required to fill in the data needed
<script src="library.js"></script>
<b id="chakra"></b>
<div id="planet"></div>
<script>
var index = setChakra(0);
var planetConection = "";
function setChakra(index){
document.getElementById("chakra").innerHTML = chakra[index];
while (index < chakra.length){
getPlanets(index);
if (index < chakra.length-1) index++;
else index = 0;
break;
}
return index;
}
function getPlanets(chakra){
var planetIndex = 0;
document.getElementById("planet").innerHTML = "";
while( planetIndex < chakraPlanets[chakra].length){
document.getElementById("planet").innerHTML = document.getElementById("planet").innerHTML + planetDesc[chakraPlanets[chakra][planetIndex]] +
"<form>" +
"<input id=\"planetStatus" + planetIndex + "\" type=\"text\" name=\"plntStat\">" +
"<button onclick=\"getPlanetConection(" + planetIndex + ")\">Click Me!</button>" +
"</form>" +
"<p id=\"status\"></p>";
planetIndex++;
}
}
function getPlanetConection(planetIndex){
planetConection = document.getElementById("planetStatus" + planetIndex).value;
document.getElementById("status").innerHTML = planetConection;
}
</script>
<button onclick = "index = setChakra(index)" >Click Me!</button>
Ok solved it button is meant to be input if i am not refreshing the page
<script src="library.js"></script>
<b id="chakra"></b>
<div id="planet"></div>
<script>
var index = setChakra(0);
var planetConection = "";
function setChakra(index){
document.getElementById("chakra").innerHTML = chakra[index];
while (index < chakra.length){
getPlanets(index);
if (index < chakra.length-1) index++;
else index = 0;
break;
}
return index;
}
function getPlanets(chakra){
var planetIndex = 0;
document.getElementById("planet").innerHTML = "";
while( planetIndex < chakraPlanets[chakra].length){
document.getElementById("planet").innerHTML = document.getElementById("planet").innerHTML + planetDesc[chakraPlanets[chakra][planetIndex]] +
"<form>" +
"<input id=\"planetStatus" + planetIndex + "\" type=\"text\" name=\"plntStat\">" +
"<input value=\"Click\" type=\"button\" onclick=\"getPlanetConection(" + planetIndex + ")\"/>" +
"</form>" +
"<p id=\"status" + planetIndex + "\"></p>";
planetIndex++;
}
}
function getPlanetConection(planetIndex){
planetConection = document.getElementById("planetStatus" + planetIndex).value;
document.getElementById("status" + planetIndex).innerHTML = planetConection;
}
</script>
<button onclick = "index = setChakra(index)" >Click Me!</button>
I think the page is reloading. Add a type attribute with value 'button' to your button.
Like so:
<button type="button" onclick = "index = setChakra(index)" >Click Me!</button>
"<button type=\"button\" onclick=\"getPlanetConection(" + planetIndex + ")\">Click Me!</button>"
This is so that the button acts as a button and not a submit button.

I have this code that works in JSFiddle but not on my site

I want to create a new button every time the post button is clicked and each new button should have its own counter. This works in JSFiddle but not when I use it.
$(function() {
$('.input_button').on('click', function() {
text = $('.input_text').val();
var btn = $("<button></button>");
btn.text("Like!");
$("body").append(btn);
btn.after("<span class='clicks'></span>")
var clicks = 0;
btn.click(function() {
clicks++;
$(this).next(".clicks").html(clicks);
});
if (text != undefined) {
post = '<div class="post test--post">' + '<img src="photo.JPG" width="20" height="25" alt=""/>' + '<p><span>jaleelg: </span></p>' + text +
'<p>Clicks: <a id="clicks">0</a></p>' + "<br>" + Date() + " " + '</div>';
new_post = $('.post_feed').append($(post))
new_post = $('.post_feed').append($(btn))
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
<h3 id="feed">My Posts</h3>
<section class="post_feed test--post_feed">
</section>
</section>
<input class="input_text test--input_text" type="text">
<button type="submit" class="input_button test--input_button">Post</button>
<div id="clicks">
</div>
You have to change in this:
btn.click(function() {
clicks++;
$(this).next(".clicks").html(clicks);
});
Like this:
btn.click(function() {
$('.clicks').html(function(i, val) { return val*1+1 });
});
This pen works:
http://codepen.io/anon/pen/ygRxOq?editors=0010
$(function() {
$("body").on("click",".like",function(e) {
clicks = $(e.target.parentElement).find("#clicks").text() / 1 + 1;
$(e.target.parentElement).find("#clicks").text(clicks);
});
$('.input_button').on('click', function() {
text = $('.input_text').val();
post = '<div class="post test--post">' +
'<img src="photo.JPG" width="20" height="25" alt=""/>' +
'<p><span>jaleelg: </span></p>' + text +
'<p>Clicks: <a id="clicks">0</a></p>' +
'<br>' + Date() + '<br>'+
'<button class="like">Like!</button>'+
'</div>';
new_post = $('.post_feed').append($(post));
});
});

New divs not creating from a newly created div

I want to remove the addcontent button once a new div is created.
Then create new divs from the new addcontent button created inside a new div.
<script>
var i = 1;
$(document).ready(function () {
$("#addcontent").click(function () {
var q = "new-question" + String(i);
alert(q);
$(".question").append('<div class="new-question" id="question' + i + '" name="question' + i + '"><b>Div is created</b><br> This is div text <br> <button id="addcontent">Add content</button></div>').show('slow');
i++;
});
});
</script>
<div class="question">
<button id="addcontent">Add content</button>
</div>
try this:
<script>
var i = 1;
$(document).ready(function () {
$(document).on('click','.addcontent',function(){
//$(".addcontent").click(function () {
if(i==1)
$(".question").html('');
var q = "new-question" + String(i);
$(".hide_button").remove();
alert(q);
$(".question").append('<div class="new-question" id="question' + i + '" name="question' + i + '"><b>Div is created</b><br> This is div text <br> <button class="addcontent hide_button">Add content</button></div>').show('slow');
i++;
});
});
</script>
<div class="question">
<button class="addcontent hide_button">Add content</button>
</div>
Just in case you want to have div inside div questions:
var i = 1;
$(document).ready(function () {
$('.question').on('click', 'button#addcontent', function () {
var $parent = $(this).parent();
$(this).remove();
var q = "new-question" + String(i);
alert(q);
$parent.append('<div class="new-question" id="question' + i + '" name="question' + i + '"><b>Div is created</b><br> This is div text <br> <button id="addcontent">Add content</button></div>').show('slow');
i++;
});
});
See demo

Javascript Specificity (Only Respond to Clicked Item)

I'm very new to Javascript and am looking for a way to have my code only respond to the clicked item in the list. (full JSFiddle here: http://jsfiddle.net/5cjPF/, although for some reason buttons aren't responsive...)
For the functions below, each applies only to a certain clicked item, however, right now only the first item that each refers to is responding. A friend of mine suggesting creating a class for each function, but I honestly have no idea where to begin and would really appreciate a push in the right direction!
<script type="text/javascript">
var submitcount = 0;
function arrow() {
if (submitcount == 0 || submitcount % 2 == 0) {
var extension = document.getElementById('one');
extension.insertAdjacentHTML('beforeend', '<div id="before-two"><div id="two"><div class="btn-group"><!----><button type="button" class="left" onclick="modify_qtyTag(1)"></button><!----><button type="button" class="tag" id=tag>synonyms</button><!----><button type="button" class="right" onclick="modify_qtyTag(0)"></button><!----></div><div class="btn-group"><button type="button" class="left" onclick="modify_qtyTag(1)"></button><!----><button type="button" class="tag" id=tag>beast</button><!----><button type="button" class="right" onclick="modify_qtyTag(0)"></button></div><p><div class="btn-group"><!----><button type="button" class="left" onclick="modify_qtyTag(1)"></button><!----><button type="button" class="tag" id=tag>antonyms</button><!----><button type="button" class="right" onclick="modify_qtyTag(0)"></button><!----></div><div class="btn-group"><button type="button" class="left" onclick="modify_qtyTag(1)"></button><!----><button type="button" class="tag" id=tag>gentle</button><!----><button type="button" class="right" onclick="modify_qtyTag(0)"></button></div></p></div></div></div>');
}
else if(document.getElementById('two')) {
var deleted = document.getElementById('before-two');
deleted.remove(deleted.selectedIndex);
}
submitcount += 1;
};
var upvotes = 0;
var votes = 0;
function modify_qty(val) {
var qty = document.getElementById('qty').value;
votes += 1;
upvotes += val;
var percent = Math.round((upvotes / votes) * 100);
document.getElementById('qty').value = percent;
}
var upvotesTag = 0;
var votesTag = 0;
function modify_qtyTag(val) {
var extension = document.getElementById('tag');
votes += 1;
upvotes += val;
var percent = Math.round((upvotes / votes) * 100);
var allThings = percent + "%," + " 100%," + " 100%," + " 100%;";
extension.style.backgroundSize = allThings;
extension.style.backgroundSize = "100%";
extension.style.backgroundSize = percent + "%, 100%, 100%, 100%";
}
</script>
The JS should be:
function modify_qtyTag(val, tagid) {
var extension = document.getElementById(tagid);
var votes = parseInt(extension.getAttribute("data-votes"), 10) + 1;
var upvotes = parseInt(extension.getAttribute("data-upvotes"), 10) + val;
var percent = Math.round((upvotes / votes) * 100);
var allThings = percent + "%," + " 100%," + " 100%," + " 100%;";
extension.style.backgroundSize = allThings;
extension.setAttribute('data-votes', votes);
extension.setAttribute('data-upvotes', upvotes);
}
The HTML would be something like:
<button type="button" class="left" onclick="modify_qtyTag(1, 'tag1')"></button>
<button type="button" class="tag" id="tag1" data-votes="0" data-upvotes="0">synonyms</button>
This adds an argument to the function that tells it which tag to update. And instead of using global variables for the votes and upvotes, it stores it in data attributes in the tag element, so that each one can have its own percentage.

Categories

Resources