I'm making a pomodoro clock with a break timer and a session timer. I'm using a single numpad to input the data into each clock by trying to nest the o'clock event to set each clock. To make it happen you click the display for the clock and then start inputting the buttons. There is 0-9 a delete button and an enter button. I haven't been able to get it to even display anything for either function. So I'm starting to wonder if what I'm trying to do would even work? Just looking for whether you can nest on click events and if so what I'm doing wrong. Or another method for what I'm looking to do. Made a fiddle to view it minimize the js and css windows. https://jsfiddle.net/zackluckyf/jhe98j05/1/
$(".session-time-clock").click(function(){
// changes the color to make it flash, add a duration and then change it back
$(".num-button").css("background-color", "#BCC6CC");
function myFunction() {
myVar = setTimeout(changeBackground, 500);
}
function changeBackground() {
$(".num-button").css("background-color", "#575e62");
}
myFunction();
sessionTimeClock = "00:00";
counter = 4;
/*
Will this work?
*/
$("button").click(function(){
// gets button text label
var input = $(this).text();
// if, else if chain for calculator functions
if(input !== "Start" && input !== "Pause" && input !== "Reset" && input !== "X" && input !== "Enter" && counter > -1)
{
if(counter === 4)
{
sessionTimeClock = sessionTimeClock.slice(0,counter-1) + input;
}
if(counter === 3)
{
sessionTimeClock = "00:" + input + sessionTimeClock.slice(4);
}
if(counter === 1)
{
sessionTimeClock = "0" + input + sessionTimeClock.slice(2);
}
if(counter === 0)
{
sessionTimeClock = input + sessionTimeClock.slice(1);
}
counter--;
if(counter === 2)
{
counter--;
}
}
else if(input === "X")
{
if(counter === 3)
{
sessionTimeClock = "00:0" + sessionTimeClock.slice(4);
}
else if(counter === 1)
{
sessionTimeClock = "00:" + sessionTimeClock.slice(3);
}
else if(counter === 0)
{
sessionTimeClock = "0" + sessionTimeClock.slice(1);
}
}
else if(input === "Enter")
{
return;
}
$(".session-time-clock").text("hello");
});
});
$(".break-time-clock").click(function(){
$(".num-button").css("background-color", "#BCC6CC");
function myFunction() {
myVar = setTimeout(changeBackground, 500);
}
function changeBackground() {
$(".num-button").css("background-color", "#575e62");
}
myFunction();
breakTimeClock = "00:00";
counter = 4;
$("button").click(function(){
// gets button text label
var input = $(this).text();
// if, else if chain for calculator functions
if(input !== "Start" && input !== "Pause" && input !== "Reset" && input !== "X" && input !== "Enter" && counter > -1)
{
if(counter === 4)
{
breakTimeClock = breakTimeClock.slice(0,counter-1) + input;
}
if(counter === 3)
{
breakTimeClock = "00:" + input + breakTimeClock.slice(4);
}
if(counter === 1)
{
breakTimeClock = "0" + input + breakTimeClock.slice(2);
}
if(counter === 0)
{
breakTimeClock = input + breakTimeClock.slice(1);
}
counter--;
if(counter === 2)
{
counter--;
}
}
else if(input === "X")
{
if(counter === 3)
{
breakTimeClock = "00:0" + breakTimeClock.slice(4);
}
else if(counter === 1)
{
breakTimeClock = "00:" + breakTimeClock.slice(3);
}
else if(counter === 0)
{
breakTimeClock = "0" + breakTimeClock.slice(1);
}
}
else if(input === "Enter")
{
return;
}
$(".break-time-clock").text(breakTimeClock);
});
});
The supplied code is not identical to the jsfiddle. I will relate to the jsfiddle:
You have this code:
$("button").click(function(){
if(input === "Start")
{
// start clock code
}
else if(input === "Pause")
{
// pause clock code
}
else if(input === "Reset")
{
sessionTimeClock = "00:00";
breakTimeClock = "00:00";
}
return true;
});
This is the first time you assign a click handler to "button" and therefore it gets called first.
The "input" variable is not defined, and therefore the other handlers are not called. (You can see an error in the Dev Tools console).
Related
My knowledge is limited, so I'm just praying y'all will enlighten me who knows bare minimum of JS. I want to bypass a timer that makes it unable to go to the next page (I need 35s every single time and that's a lot considering some lessons have over 200 slides). How do I write a script for tampermonkey to make it show the link to the next page instantly?
// Obsługa przycisku Dalej
function goNext(vIsExam) {
// Przycisk nieaktywny - blokada przejścia
if (document.getElementById("pNext").rel != 'enabled') return false;
if (vIsExam==1) {
} else {
location.href='../sql/MemSql.php?pRun=MemCourseGoNext&pCourseResultId=262261&pCourseLessonId=227436';
}
} // function
// Aktywacja przycisku Dalej
function waitNextLesson(vTimeLeft, vTimer) {
setCookie('cLessonTime',vTimeLeft);
if (vTimeLeft > 0) {
document.getElementById('pNext').rel = 'disabled';
document.getElementById('pNextDiv').className = 'CourseInactive';
if (vTimer == 0) {
document.getElementById('pNextIcon').className = 'FontAwesome';
document.getElementById('pNextIcon').innerHTML = vTimeLeft;
} else {
document.getElementById('pNextIcon').className = 'FontAwesome';
document.getElementById('pNextIcon').className = 'FontAwesome FontAwesomeArrowRight';
}
document.getElementById('pNextName').innerHTML = 'CZEKAJ';
vTimeLeft = vTimeLeft - 1;
setTimeout("waitNextLesson("+vTimeLeft+","+vTimer+")",1000);
} else {
document.getElementById('pNext').rel = 'enabled';
document.getElementById('pNextDiv').className = '';
document.getElementById('pNextIcon').className = 'FontAwesome FontAwesomeArrowRight';
document.getElementById('pNextIcon').innerHTML = '';
document.getElementById('pNextName').innerHTML = 'NASTĘPNY SLAJD';
if (document.getElementById('iLessonAutoPlay').checked == true) document.getElementById('pNext').click();
}
} // function
// Obsługa LessonAutoPlay
function jLessonAutoPlay(e) {
setCookie('LessonAutoPlay', document.getElementById('iLessonAutoPlay').checked);
jStopPropagation(e);
} // function
//if (getCookie('LessonAutoPlay') == 'true') document.getElementById('iLessonAutoPlay').checked = true;
// Obsługa skrótów klawiaturowych (strzałka [<] i [>])
$("body").keyup(function(oEvent){
// Sprawdzenie czy można obsługiwać skróty
if (document.getElementById('DIALOG').style.display == 'none' && document.getElementById('LOADER').style.display == 'none') {
// Klawisz [<]
if (oEvent.keyCode == 37) {
document.getElementById("pPrev").click();
}
// Klawisz [>]
if (oEvent.keyCode == 39) {
if (document.getElementById("pNext").rel == 'enabled') {
document.getElementById("pNext").click();
}
}
}
});
I built a trivia game and if you run out of time then the function score() I wrote runs grades your game. This function is also tied to the submit button. So the issue arises when you finish the quiz with time remaining; because once you submit your score if the time goes to zero before you click try again it doubles your score.
How can get around this issue; I'm open to fixing it in the timer function or writing another function to prevent it from grading twice.
side note the try again button can't reset the page per requirements so I have the start button begin the countdown() (timer).
So the function I need is to check if score has been run and if it has don't run it again ; then the count has to reset when you click the start button.
var button = document.getElementById("main-button")
var taButton = document.getElementById("ta-button")
var quizText = document.getElementById("quiz")
var correct = 0;
var incorrect = 0;
var notAnswered = 0;
var correctText = document.getElementById("correct-text")
var incorrectText = document.getElementById("incorrect-text")
var notAnsweredText = document.getElementById("notAnswered-text")
var timeLeft = 70;
var timeLeftText = document.getElementById("timeLeft-text")
var elem = document.getElementById('some_div');
var timerId = setInterval(countdown, 1000);
// timer function
function countdown() {
if (timeLeft == 0) {
clearTimeout(timerId);
score();
} else {
timeLeftText.textContent = "Time Remaining " + timeLeft;
timeLeft--;
}
function start() {
document.getElementById("main-button").style.display = "none";
document.getElementById("quiz").style.display = "block";
document.getElementById("some_div").style.display = "inline-block";
timeLeft = 70;
countdown();
timeLeftText.textContent = "Time Remaining " + timeLeft;
}
function score() {
correct = 0;
incorrect = 0;
notAnswered = 0;
var question1
var question2
var question3
var question4
var question5
var question6
var question7
var question8
var question9
var question10
// checks if the value of or radio is null.
if (document.querySelector('input[name="question1"]:checked') === null) { notAnswered++;
}
// if it has a value it logs the value
// then takes the value that was stored to the radio button and clears it; resetting or buttons.
else { question1 = document.querySelector('input[name="question1"]:checked').value;
document.querySelector('input[name="question1"]').checked=false;
// This checks the value we stored and then determines if it that value is the correct answer.
if (question1 === "d") {
correct++;
}
else if ((question1 === "a") || (question1 === "b") || (question1 === "c")) {
incorrect++;
}}
// question 2.
if (document.querySelector('input[name="question2"]:checked') === null) { notAnswered++;
}
else { question2 = document.querySelector('input[name="question2"]:checked').value;
document.querySelector('input[name="question2"]').checked=false;
if (question2 === "d") {
correct++;
}
else if (question2 === "a" || "b" || "c") {
incorrect++;
}}
// question 3.
if (document.querySelector('input[name="question3"]:checked') === null) { notAnswered++;
}
else { question3 = document.querySelector('input[name="question3"]:checked').value;
document.querySelector('input[name="question3"]').checked=false;
if (question3 === "a") {
correct++;
}
else if (question2 === "b" || "c" || "d") {
incorrect++;
}}
// question 4
if (document.querySelector('input[name="question4"]:checked') === null) { notAnswered++;
}
else { question4 = document.querySelector('input[name="question4"]:checked').value;
document.querySelector('input[name="question4"]').checked=false;
if (question4 === "d") {
correct++;
}
else if (question4 === "a" || "b" || "c") {
incorrect++;
}}
// question 5
if (document.querySelector('input[name="question5"]:checked') === null) { notAnswered++;
}
else { question5 = document.querySelector('input[name="question5"]:checked').value;
document.querySelector('input[name="question5"]').checked=false;
if (question5 === "d") {
correct++;
}
else if (question5 === "a" || "b" || "c") {
incorrect++;
}}
// question 6
if (document.querySelector('input[name="question6"]:checked') === null) { notAnswered++;
}
else { question6 = document.querySelector('input[name="question6"]:checked').value;
document.querySelector('input[name="question6"]').checked=false;
if (question6 === "c") {
correct++;
}
else if (question6 === "a" || "b" || "c") {
incorrect++;
}}
// question 7
if (document.querySelector('input[name="question7"]:checked') === null) { notAnswered++;
}
else { question7 = document.querySelector('input[name="question7"]:checked').value;
document.querySelector('input[name="question7"]').checked=false;
if (question7 === "a") {
correct++;
}
else if (question7 === "a" || "b" || "c") {
incorrect++;
}}
// question 8
if (document.querySelector('input[name="question8"]:checked') === null) { notAnswered++;
}
else { question8 = document.querySelector('input[name="question8"]:checked').value;
document.querySelector('input[name="question8"]').checked=false;
if (question8 === "b") {
correct++;
}
else if (question8 === "a" || "b" || "c") {
incorrect++;
}}
// question 9
if (document.querySelector('input[name="question9"]:checked') === null) { notAnswered++;
}
else { question9 = document.querySelector('input[name="question9"]:checked').value;
document.querySelector('input[name="question9"]').checked=false;
if (question9 === "c") {
correct++;
}
else if (question9 === "a" || "b" || "c") {
incorrect++;
}}
// question10
if (document.querySelector('input[name="question10"]:checked') === null) { notAnswered++;
}
else { question10 = document.querySelector('input[name="question10"]:checked').value;
document.querySelector('input[name="question10"]').checked=false;
if (question10 === "c") {
correct++;
}
else if (question10 === "a" || "b" || "c") {
incorrect++;
}}
// this toggles what is visible on their screen.
document.getElementById("quiz").style.display = "none";
document.getElementById("scoreBox").style.display = "block";
document.getElementById("some_div").style.display = "none";
document.getElementById("ta-button").style.display = "inline-block";
// this is the text for our score box
correctText.textContent = "Correct " + correct;
incorrectText.textContent = "Incorrect " + incorrect;
notAnsweredText.textContent = "Not Answered " + notAnswered;
}
function reset() {
// this toggles what is visible on their screen.
document.getElementById("quiz").style.display = "none";
document.getElementById("some_div").style.display = "none";
document.getElementById("ta-button").style.display = "none";
document.getElementById("scoreBox").style.display = "none";
document.getElementById("main-button").style.display = "block";
// this resets the score
correct = 0;
incorrect = 0;
notAnswered = 0;
// allows the start button to be clicked up to 20 mins after the ta button, so that the score function does start before the game.
timeLeft = 12000;
}
<div id="button-container">
<div id="ta-button">
<p id="main-button"><button type="button" class=" btn-lg btn-block text-light "
onclick="reset()"><i class="fas fa-sync"></i> Try Again? <i class="fas fa-sync"></i></button></p>
</div>
</div>
<div id="button-content" class="container">
<p id="main-button"><button type="button" class=" btn-lg btn-block text-light "
onclick="start();countdown()"><i class="fas fa-user-astronaut"></i> Start
Quiz. <i class="fas fa-user-astronaut"></i></button></p>
</div>
Try this.
var timerId = null;
var timeLeft = 70;
function countDown() {
if (timerId) {
clearTimeout(timerId);
}
//do what ever
if (timeLeft < 1) {
//do something else
//then return
return 0;
}
else {
timerId = setTimeout(countDown, 1000);
}
}
function start() {
//do whatever
timerId = setTimeout(countDown, 1000);
}
If you need more info on timers in javascript check out https://www.w3schools.com/jsref/met_win_settimeout.asp
I want to scroll to searched word one by one when I click down button. Please see Fiddle for code implemented
$('#searchfor').keypress(function(){
var page = $('#all_text');
var pageText = page.text().replace("<span>","").replace("</span>");
var searchedText = $('#searchfor').val();
var theRegEx = new RegExp("("+searchedText+")", "igm");
var newHtml = pageText.replace(theRegEx ,"<span>$1</span>");
page.html(newHtml);
});
see this example : http://jsfiddle.net/kevalbhatt18/ju6xxwvb/13/
i used js from hear Search and Highlight in jQuery
and button login is wrriten
var find = function(results, type, counter, adjPx, $el) {
if (results.length > 0) {
if (type === 'next') {
if (counter > 0 && results.length == counter) {
counter = 0;
}
} else if (type === 'prev') {
if (counter < 0) {
counter = results.length - 1;
} else if (counter === results.length) {
counter = counter - 2;
}
}
results.removeClass("active");
$(results[counter]).addClass("active");
if ($el) {
$('html,body').animate({
scrollTop: $(results[counter]).offset().top - adjPx
}, 100);
} else {
$el.animate({
scrollTop: $(results[counter]).offset().top - adjPx
}, 100);
}
counter = (type === 'prev') ? counter - 1 : counter + 1;
}
return counter;
};
I have a typing speed test with a textarea and I have I paragraph split into spans. Every time the user hits space, it highlights the next span. Then I split the textarea val() and compare the two at the end. I have everything working except I cannot get the enter key to do what I want it to do. I need it to act like the space bar(in the background) and act as the enter key on screen.
$(function() {
//APPEARANCE
$('#error').hide();
$('#oldTextOne').hide();
$('#oldTextTwo').hide();
$('#oldTextThree').hide();
$('#oldTextFour').hide();
$('#oldTextFive').hide();
$('.linkBox').hover(function() {
$(this).removeClass('linkBox').addClass('linkHover');
}, function() {
$(this).removeClass('linkHover').addClass('linkBox');
});
//FUNCTIONALITY VARIABLES
var min = '5';
var sec = '00';
var realSec = 0;
var errorTest = "hasn't started yet";
var oldTextVal;
var para;
// PICK A RANDOM PARAGRAPH
function pickRandom() {
var date = new Date();
date = date.getTime();
date += '';
var dateSplit = date.split('');
var temp = dateSplit.length - 1;
var picker = dateSplit[temp];
if (picker === '0' || picker === '1') {
para = $('#oldTextOne').text();
}
else if (picker === '2' || picker === '3') {
para = $('#oldTextTwo').text();
}
else if (picker === '4' || picker === '5') {
para = $('#oldTextThree').text();
}
else if (picker === '6' || picker === '7') {
para = $('#oldTextFour').text();
}
else {
para = $('#oldTextFive').text();
}
var splitPara = para.split(' ');
for (i in splitPara) {
$('#oldTextBox').append('<span id="pw' + i + '">' + splitPara[i] + '</span> ');
}
}
pickRandom();
//FUNCTION FOR TIMER
//APPEARANCE
function show() {
$('#timer').text(min + ' : ' + sec);
}
show();
//COUNT-DOWN
var count = function() {
sec = +sec - 1;
sec += '';
realSec++;
if (+sec === -1) {
sec = '59';
min -= 1;
min += '';
}
if (sec.length === 1) {
sec = '0' + sec;
}
show();
if (sec === '00' && min === '0') {
clearInterval(run);
checkIt();
}
};
// TYPE THE TEXT INTO #TYPEDTEXTBOX
$('#pw0').addClass('green');
var lastLetter;
$('#typedTextBox').focus().keypress(function() {
if (errorTest === "hasn't started yet") {
errorTest = 'running';
run = setInterval(count, 1000);
}
//STOP ERRORS FROM PEOPLE HITTING SPACE BAR TWICE IN A ROW !!NOT WORKING IN IE8
var thisLetter = event.which;
if (lastLetter === 32 && event.which === 32) {
event.preventDefault();
}
lastLetter = thisLetter;
}).keyup(function() {
//STOP ERRORS FROM BACKSPACE NOT REGISTERING WITH KEYPRESS FUNCTION
if (event.which === 8) {
lastLetter = 8;
}
if (event.which === 13) {
?????????????????????????????????????????????
}
//SPLIT THE TYPED WORDS INTO AN ARRAY TO MATCH THE OLD TXT SPANS (TO HIGHLIGHT THE CURRENT WORD IN OLDTXT)
var typedWords = $(this).val().split(' ');
var temp = typedWords.length - 1;
var oldTemp = temp - 1;
var stopErrors = temp + 1;
$('span:nth(' + temp + ')').addClass('green');
$('span:nth(' + oldTemp + ')').removeClass('green');
$('span:nth(' + stopErrors + ')').removeClass('green');
//SCROLL
if (typedWords.length < 50) {
return;
}
else if (typedWords.length > 50 && typedWords.length < 100) {
$('#oldTextBox').scrollTop(30);
}
else if (typedWords.length > 100 && typedWords.length < 150) {
$('#oldTextBox').scrollTop(60);
}
else if (typedWords.length > 150 && typedWords.length < 200) {
$('#oldTextBox').scrollTop(90);
}
else if (typedWords.length > 200) {
$('#oldTextBox').scrollTop(120);
}
//KEEP FOCUS IN THE TYPING AREA
}).blur(function() {
if (errorTest !== 'done') {
$(this).focus();
}
});
//COMPARE
//MAKE AN ARRAY OF THE OLDTEXT
var oldWords = para.split(' ');
//FUNCTION TO DISPLAY RESULTS
var checkIt = function() {
errorTest = 'done';
var correct = 0;
var typed = $('#typedTextBox').val();
var typedWords = typed.split(' ');
$('#typedTextBox').blur();
for (i = 0; i < typedWords.length; i++) {
if (typedWords[i] === oldWords[i]) {
correct += 1;
}
}
var errors = typedWords.length - correct;
var epm = (errors / realSec) * 60;
var wpm = Math.round(( ($('#typedTextBox').val().length / 5 ) / realSec ) * 60);
var realWpm = Math.round(wpm - epm);
//SHOW RESULTS
$('#oldTextBox').html('<br><span id="finalOne">WPM : <strong>' + realWpm + ' </strong></span><span class="small">(error adjusted)</span><br><br><span id="finalTwo">You made ' + errors + ' errors </span><br><span id="finalThree">Total character count of ' + $('#typedTextBox').val().length + '</span><br><span id="finalFour">Gross WPM : ' + wpm + '</span>');
};
//STOP BUTTON APPEARANCE AND FUNCTIONALITY
$('#stop').mouseover(function() {
$(this).addClass('stopHover');
}).mouseout(function() {
$(this).removeClass('stopHover');
}).click(function() {
if (errorTest === 'running') {
checkIt();
clearInterval(run);
errorTest = 'done';
}
});
});
try this:
//ENTER KEY
if (event.which === 13) {
//event.stopPropagation(); or
event.preventDefault();
//simulate spacebar
$(window).trigger({type: 'keypress', which: 32, keyCode: 32});
}
#james - Thanks for the help. I found a better way of thinking about the problem. Instead of changing the enter key action, I changed the split function to var typedWords = typed.split(/[ \r\n]+/);
I am looking to make a checkbox that when unchecked, will turn off a certain function in a .js file. Can someone help me?
popup.html
HTML Check box:
content.js
Turn off this function:
var tweet = new Array();
var tweetName = new Array();
function linkSnipe() {
for (var i = 0; i < 5; i++) {
tweetName[i] = document.getElementsByClassName("fullname js-action-profile-name show-popup-with-id")[0].innerHTML;
tweet[i] = document.getElementsByClassName("js-tweet-text")[i].innerHTML;
}
if (tweet[0].match(shoeName) == shoeName && tweet[0].match(filterer) != filterer && tweet[0].match(filter2) != filter2) {
if(checkon == "Tweets"){
document.getElementsByClassName("twitter-timeline-link")[0].click();
update();
}
}
else if (tweet[1].match(shoeName) == shoeName && tweet[1].match(filterer) != filterer && tweet[1].match(filter2) != filter2) {
if(checkon == "Tweets"){
document.getElementsByClassName("twitter-timeline-link")[1].click();
update();
}
}
else if (tweet[2].match(shoeName) == shoeName && tweet[2].match(filterer) != filterer && tweet[2].match(filter2) != filter2) {
if(checkon == "Tweets"){
document.getElementsByClassName("twitter-timeline-link")[2].click();
update();
}
}
else if (tweet[3].match(shoeName) == shoeName && tweet[3].match(filterer) != filterer && tweet[3].match(filter2) != filter2) {
if(checkon == "Tweets"){
document.getElementsByClassName("twitter-timeline-link")[3].click();
update();
}
}
else if (tweet[4].match(shoeName) == shoeName && tweet[4].match(filterer) != filterer && tweet[4].match(filter2) != filter2) {
if(checkon == "Tweets"){
document.getElementsByClassName("twitter-timeline-link")[4].click();
update();
}
}
else if(checkon == "Tweets") {
location.reload();
}
}
setTimeout("linkSnipe()", 250);
}
When the checkbox is checked, redefine the function as:
<input type=checkbox ..... onchange="doit()">
function doit() {
window.linkSnipe=function() {}
}
I've used this too:
function doit() {
window['linkSnipe']=function() {}
}
If you want to turn the function on and off by the checkbox:
<input type=checkbox ..... onchange="doit(this)">
var linkSnipeSave = linkSnipe;
function doit(ck) {
if (ck.checked)
window['linkSnipe']=linkSnipeSave
else {
linkSnipeSave = linkSnipe; //not sure if this line is needed...pls test
window['linkSnipe']=function() {}
}
}
You could simply have a Boolean variable that changes with the state of your check box. You could then put an if statement around the function call that will only trigger if the checkbox is checked.
http://jsfiddle.net/W5P8X/
//initialize some variables.
bike_checked = false;
car_checked = false;
//get elements by their ID from html
bike = document.getElementById("bike");
car = document.getElementById("car");
//add event listeners to the html elements we found above
bike.addEventListener("click", toggle_bike, false);
car.addEventListener("click", toggle_car, false);
//toggle bike_checked variable on click
function toggle_bike(){
if(bike_checked == true)
bike_checked = false;
else
bike_checked=true;
current_state();
}
//toggle car_checked variable on click
function toggle_car(){
if(car_checked == true)
car_checked = false;
else
car_checked=true;
current_state();
}
//output current state.
function current_state(){
if(car_checked == true)
alert('Car checked');
if(bike_checked == true)
alert('Bike checked');
}
I answered with only javascript and no jQuery, but you could probably make it a bit more concise with jQuery.
I hope this helps.