Submit button works only once on mobile - javascript

So I'm using phonegap to create an application the submit button works just as intended (not refreshing the page) on the browser but when I run it on mobile it works only once, if I press the"Go" button on mobile keyboard it works as intended just the actual submit button isn't working.
not sure if you need more information I could provide more on the code if you'd like.
JQuery I'm using:
$(function() {
$("form").submit(function() { return false; });
});
The submit button I'm using
<input id="button" class="btn btn-primary" type="submit" value="Check" onclick = "check();">
// The check function
var correct = 0;
function check (){
var answer = document.quiz.question1.value;
var answerL = answer.toLowerCase();
//var areEqual = question1.toUpperCase() === questions[pos][1].toUpperCase();
if (answerL !=null && answerL !== ''){
if (answerL == questions[pos][1]){
//$(".test").show();
$("#result").attr("src","correct.png");
$(".correct_answer").css("visibility", "visible");
correct++;
//delete questions[pos];
questions.splice(pos, 1);
var max = questions.length -1;
//window.prompt(questions); //testing the array deletion
pos = Math.floor(Math.random() * questions.length);
document.getElementById("number_correct").className = "green";
}
else {
correct--;
document.getElementById("number_correct").className = "red";
$("#result").attr("src","wrong.png");
$(".correct_answer").css("visibility", "visible");
}
}
//$(".correct_answer").css("visibility", "hidden");
questioner ();
document.getElementById("number_correct").innerHTML = "Your Score: " + correct;
document.getElementById("after_submit").style.visibility = "visible";
$('#quiz')[0].reset();
}
document.addEventListener("DOMContentLoaded", function() {
questioner();
});

Related

How to hide button after 5 clicks jQuery?

In short I have multiple posts and each post have download button with unique data-click attribute,
For example data-click="1" for post 1 download button , data-click="2" for post 2 download button and so on. I want that if download button click 5 times for post 1 then after 5 clicks it hides , also it keeps hidden if refresh the page , I have written some code but it doesn't hide the button
<script>//this script is responsible for adding a unique data-click= 0,1,2,3,4.....n to each resume post respectively.
$(document).ready(function() {
var PostId = 2;
var i = 1;
$('.gotocls').each(function() {
jQuery(this).attr('data-click', i);
var ClickId = $(this).attr('data-click');
var LocalKey = PostId + '+' + ClickId;
if(localStorage.getItem(LocalKey)){
if(localStorage.getItem(LocalKey) == '5'){
$(this).hide();
// alert('im m new here');
}
}
else{
localStorage.setItem(LocalKey,0);
alert('im game');
}
i++
});
});
</script>
the above code add unique data click attribute to each downlaod button and check if localstorage value is 5
<script type="text/javascript">
$(document).ready(function(){
$(".gotocls").click(function() {
var PostId = 2;
var ClickId = $(this).attr("data-click");
var LocalKey = PostId + '+' + ClickId;
count = localStorage.getItem(LocalKey);
count ++;
if(count > 5){
alert(count);
localStorage.setItem(LocalKey, 5);
$(this).hide();
}
else{
alert(count);
alert('imnot here');
localStorage.setItem(LocalKey, count);
}
});
});
</script>
and my html code
<a class="dkpdf-button gotocls" href="javascript:return false;">Download Now</a>
For a better understanding, I set the simple code
HTML
<div>
<button id="gotocls" class="gotocls">Download</button>
</div>
Sctipt
<script type="text/javascript">
$(document).ready(function () {
var LocalKey = "Click_Count"; // set key paramater
count = localStorage.getItem(LocalKey); // get data from local storage
if (count >= 5) //condition - if click count equal or greater than 5
{
$(".gotocls").hide(); // button hide
}
$(".gotocls").click(function () {
//var PostId = 2;
//var ClickId = $(this).attr("data-click");
count++;
if (count >= 5) {
alert(count);
localStorage.setItem(LocalKey, 5);
$(this).hide();
}
else {
alert(count);
alert('imnot here');
localStorage.setItem(LocalKey, count);
}
});
});
</script>
you can change javascript as per your requirements, this will work on client-side

JS: setInterval running as if there were multiple intervals set

So, I've been trying to figure out JS, and what better way to do so than to make a small project. It's a small trivia game, and it has a question timer I've made using setInterval. Unfortunately, after answering multiple questions, the interval's behaviour gets very weird - it runs the command twice every time. I guess it's my faulty implementation of buttonclicks?
By the way, if my code is awful I am sorry, I've been desperate to fix the issue and messed with it a lot.
function startGame(){
if (clicked === true){
return;
}
else{
$("#textPresented").html("Which anthem is this?");
$("#button").css("display", "none");
currentCountry = getRndInteger(0,8);
console.log(currentCountry);
var generatedURL = anthemnflags[currentCountry];
console.log(generatedURL);
audios.setAttribute("src", generatedURL);
audios.play();
$("#button").html("I know!");
$("#button").css("display", "block");
$("#button").click(function () {
continueManager();
});
y=10;
console.log("cleared y" + y);
x = setInterval(function(){
y = y - 1;
console.log("Counting down..." + y)
}, 1000);
console.log("INTERVAL SET");
}
}
Here is the console output:
cleared y10 flaggame.js:59:17
INTERVAL SET flaggame.js:64:17
AbortError: The fetching process for the media resource was aborted by the user agent at the user's request. flaggame.js:49
Counting down...9 flaggame.js:62:20 ---- THESE TWO ARE BEING PRINTED AT THE SAME TIME
Counting down...8 flaggame.js:62:20 ---- THESE TWO ARE BEING PRINTED AT THE SAME TIME
Counting down...7 flaggame.js:62:20
Counting down...6 flaggame.js:62:20
Counting down...5 flaggame.js:62:20
Counting down...4 flaggame.js:62:20
Counting down...3 flaggame.js:62:20
Counting down...2 flaggame.js:62:20
Counting down...1 flaggame.js:62:20
Counting down...0
THE REST OF MY CODE:
function middleGame(){
$("#button").css("display", "none");
var n = document.querySelectorAll(".flagc").length;
correctIMG = getRndInteger(0,n-1);
showFlags();
var taken = new Array();
for (var i = 0; i < n; ++i){
if (i === correctIMG){
images[i].attr("src", "res/" + flagsfiles[currentCountry]);
taken[currentCountry] = true;
}
else{
var randomFlag = getRndInteger(0, flagsfiles.length);
if (randomFlag !== currentCountry && taken[randomFlag] !== true){
images[i].attr("src", "res/" + flagsfiles[randomFlag]);
taken[randomFlag] = true;
}
}
}
$(".flagc").click(function(){
clickregister(this);
});
}
function continueManager(){
if (!clicked){
audios.pause()
clearInterval(x);
x = 0;
clicked = true;
middleGame();
return;
}
}
function clickregister(buttonClicked){
if ($(buttonClicked).attr("id") != correctIMG){
points = points - 1;
flagARR[$(buttonClicked).attr("id")].css("display", "none");
console.log("INCORRECT");
}
else{
if (y >= 0) {
var addedPoints = 1 + y;
points = points + addedPoints;
$("#points").html(points);
}
else{
points = points + 1;
}
hideFlags();
clicked = false;
startGame();
}
}
$(function(){
hideFlags();
$("#textPresented").html("When you're ready, click the button below!");
$("#button").html("I am ready!");
$("#button").click(function () {
if (!gameStarted){
gameStarted = true;
alert("STARTING GAME");
startGame();
}
});
});
Basically this is how it works:
When the "I am ready" button is clicked, startGame() is called. It plays a random tune and counts down, until the player hits the "I know" button. That button SHOULD stop the interval and start the middleGame() function, which shows 4 images, generates a random correct image and awaits input, checks if it's true, then launches startGame() again.
The first and second cycles are perfect - after the third one things get messy.
I also noticed that the "INCORRECT" log gets printed twice, why?
EDIT: here is the minimized code that has the same issue:
var x;
var gameStarted = false;
var y;
var clicked;
$(function(){
$("#button").click(function () {
if (!gameStarted){
gameStarted = true;
startGame();
}
});
});
function startGame(){
console.log("startgame()");
if (clicked === true){
return;
}
else{
console.log("!true");
$("#button").css("display", "block");
$("#button").click(function () {
continueManager();
});
y=10;
x = setInterval(function(){
y = y - 1;
console.log(y);
}, 1000);
}
}
function continueManager(){
if (!clicked){
clearInterval(x);
x = 0;
clicked = true;
middleGame();
return;
}
}
function middleGame(){
$("#button").css("display", "none");
var taken = new Array();
$(".flagc").click(function(){
clickregister(this);
});
}
function clickregister(buttonClicked){
console.log("clickgregister");
//Irrelevant code that checks the answers
clicked = false;
startGame();
}
EDIT2: It appears that my clickregister() function gets called twice, and that function then calls startGame() twice.
EDIT3: I have found the culprit! It's these lines of code:
$(".flagc").click(function(){
console.log("button" + $(this).attr("id") + "is clicked");
clickregister(this);
});
They get called twice, for the same button
I fixed it!
It turns out all I had to do was to add
$(".flagc").unbind('click');
Before the .click() function!
You need to clear the interval first then call it again. You can do that by creating a variable outside of the event listener scope and in the event listener check if the variable contains anything if yes then clear the interval of x. After clearing the interval you can reset it.
Something like this:
<button class="first" type="submit">Button</button>
const btn = document.querySelector('.first');
let x;
btn.addEventListener("click", () => {
x && clearInterval(x)
x = setInterval(() => console.log("yoo"), 500)
})
This is because if you don't clear the interval of x it will create a new one on every button press.

How can I use localStorage for storing clicks

I am trying to save the amount of clicks on a button in a textbox with localStorage, but whenever I reload the page, all the data is cleared. Here is my code:
var i = 0; // i is the number of clicks. the number of clicks is set to 0
when page is
// loaded.
function countClick() { // The next 3 lines of code are executed when the
Kill a cat // button is clicked
i++;
alert("You have clicked " + i + " cats so far"); // Make message box
localStorage.setItem("count", "i")
document.getElementById("count").value = i ; // Edits the 'clicks clicked'
text box
// Saves number of clicks, so when you close // or open the page, your
progress still exists.
}
function clear() {
document.getElementById("count").value = 0 ;
}
window.onload = function(){
var val = localStorage.getItem('value'); // or localStorage.value
if(val === null)
val = "i";
document.getElementById("myData").value = val;
}
window.onbeforeunload = function(){
localStorage.setItem('value', document.getElementById("myData").value);
localStorage.value = document.getElementById("myData").value
}
Please help.
Thanks to all the other examples from the other people, used in here.
In this function, you reset your localStorage item before page load...
window.onbeforeunload = function(){
localStorage.setItem('value', document.getElementById("myData").value);
localStorage.value = document.getElementById("myData").value
}
It's normal there is no data when you refresh.
Just try somethink more simple like this without other function :
var i = 0;
function countClick() {
i++;
localStorage.setItem("count", i)
document.getElementById("count").value = i ;
}
window.onload = function(){
var val = localStorage.getItem('count');
document.getElementById("count").value = val;
}

How to set a value of a variable in a "child" javascript file from the "parent"?

In my index.php I have a script which toggles a sidebar.
$(function() {
// Open the Sidebar
$(".sidebar.right").trigger("sidebar:open");
// Toggle the Sidebarbutton to close
$(".open-close-button").toggleClass("open");
count = "1";
});
There is a "open/close" button which toggles the sidebar aswell. - Now, if i set the sidebar to "open" I need to tell the toggle-button to close, if someone clicks it - and I do that by setting "count" to "1".
"Count" is a "global-variable" - I think. I´m new to javascript, but it´s in no function. Look here, thats the "sidebar-toggle-script" sidebarhandlers.js:
var count = "0";
var open = "open";
var close = "close";
$(".sidebaropenclose").on("click", function () {
var $this = $(this);
var side = $this.attr("data-side");
if (count == "0") {
$this = $(this);
side = $this.attr("data-side");
$(".sidebar." + side).trigger("sidebar:" + open);
count++;
return false;
}
if (count == "1") {
$this = $(this);
side = $this.attr("data-side");
$(".sidebar." + side).trigger("sidebar:" + close);
count = 0;
return false;
}
In the "header" of my "index.php" I initialize the script with:
<script src="js/sidebarhandlers.js"></script>
The question is how i send the "count" from my "index.php" to "sidebarhandlers.js". - My version doesn´t work.

clearInterval and setInterval within if else statement

type in textarea..on textarea change it updates counter of "char_count" once it reaches at 0 it blinks..then hit backspace till counter reaches at 1
the issue is it wont stop blinking
<div>
<textarea rows="10"></textarea>
<div class="char_count">5 characters remaining</div>
</div>
here is jsfiddle
https://jsfiddle.net/mzx79os2/1/
I have looked into the fiddle you've attached. There are two issues,
On keyup you're attaching jQuery animations each time on keyup. So clearing the interval wont help you.
jQuery animation has to be stopped, use $(element).stop(true, true)
I have updated the jsFiddle and also added a check isBlinking to attach animation only once.
Check this link
https://jsfiddle.net/mzx79os2/8/
var descriptionTextarea = $("textarea");
var char_count = ".char_count";
var textMax = 5;
var isRunning = false;
var clearInt = 0;
$(char_count).html(textMax + ' characters remaining');
descriptionTextarea.on("keyup", function(e) {
e.stopPropagation();
var textLength = $(this).val().length;
var textRemaining = textMax - textLength;
var selfCharCounter = $(this).parent().find(char_count);
function blink() {
$(selfCharCounter).fadeOut(500).fadeIn(500);
};
if (textRemaining <= 0 && !isRunning) {
selfCharCounter.css("color", "red");
clearInt = setInterval(blink, 500);
isRunning = true;
} else if (textRemaining > 0 && isRunning) {
isRunning = false;
selfCharCounter.css("color", "");
$(selfCharCounter).stop(true, true).fadeOut();
$(selfCharCounter).stop(true, true).fadeIn()
clearInterval(clearInt);
clearInt = 0;
}
selfCharCounter.html(textRemaining + ' characters remaining');
});
There are multiple problems with your code:
In your case clearInt is set inside the keyup handler (so after every keypress you reset clearint to 0 so you don't clear the right one)
You set multiple intervals on every keypress and you just remove the last one, you should only add an interval if there's not one already running
To stop the animation you should use the stop method of jQuery
You should also paste the code with the problem on SO
https://jsfiddle.net/mzx79os2/13/
var $descriptionTextarea = $("textarea");
var $char_count = $(".char_count");
var textMax = 5;
var animation, animationInProcess;
$char_count.html(textMax + ' characters remaining');
function blinkStart(selfCharCounter) {
console.log('run blink');
animationInProcess = true;
animation = setInterval(function(selfCharCounter){
if( !animationInProcess){
blinkStop(selfCharCounter)
return;
}
$(selfCharCounter).fadeOut(500).fadeIn(500);
}, 500, selfCharCounter);
};
function blinkStop(selfCharCounter){
console.log('stop blink');
$(selfCharCounter).stop(true, true).show();
clearInterval(animation);
};
$descriptionTextarea.on("keyup",function(e){
e.stopPropagation();
var textLength = $(this).val().length;
var textRemaining = textMax - textLength;
var selfCharCounter = $(this).next();
if(textRemaining <= 0){
(!animationInProcess) && blinkStart(selfCharCounter);
selfCharCounter.css("color","red");
}else{
animationInProcess = false;
selfCharCounter.css("color","");
}
selfCharCounter.html(textRemaining + ' characters remaining');
});

Categories

Resources