How to hide button after 5 clicks jQuery? - javascript

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

Related

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.

Clear Interval + message and replace with a link

How can I clean interval+message and replace those with a link.
Below code is opening a link after 10 seconds in new window. When I get back to that page, message showing You will redirect in 0 seconds
What I want is, after 10 seconds (after opening link in new tab) the counter and message will replace with a new message and link. i.e. If you are not redirected to the link Click Here to go to the link.
var count = 10;
var counter;
function start(){
counter = setInterval(timer, 1000);
}
function timer() {
var output = document.getElementById("displaySeconds");
output.innerHTML = count;
count--;
if (count < 0) {
clearInterval(counter);
window.open("https://www.google.com");
return;
}
}
window.addEventListener("load", start, false);
<br>You will redirect in <span id="displaySeconds">10</span> seconds.<br />
You can create a separate div with the text when the user is not redirected with the display property set to none (display: none). When the timer expires, you can hide the original text and show the alternative version.
There is a working jsfiddle below. I modified the counter to 4 seconds not to wait too much, you can adjust it how you want.
var count = 4;
var counter;
function start() {
counter = setInterval(timer, 1000);
}
function timer() {
var output = document.getElementById("displaySeconds");
output.innerHTML = count;
count--;
if (count < 0) {
clearInterval(counter);
window.open("https://www.google.com");
let originalText = document.getElementById("original");
let noRedirectText = document.getElementById("noredirect");
originalText.style.display = "none";
noRedirectText.style.display = "block";
}
}
window.addEventListener("load", start, false);
<div>
<div id="original">
You will be redirected in <span id="displaySeconds">4</span> seconds.
</div>
<div style="display: none" id="noredirect">
If you are not redirected click here to go to the link.
</div>
</div>
Cheers!
Just add code to the interval function that hides the first message and shows the other.
var count = 5;
var output = document.getElementById("displaySeconds");
var counter = null;
function timer() {
output.textContent = count;
count--;
if (count < 0) {
clearInterval(counter);
window.open("https://www.google.com");
// Hide the first message and show the second:
document.querySelector(".redirect1").classList.add("hidden");
document.querySelector(".redirect2").classList.remove("hidden");
}
}
addEventListener("load", function(){
couner = setInterval(timer, 1000);
});
.hidden { display:none; }
<div class="redirect1">You will redirect in <span id="displaySeconds">5</span> seconds.</div>
<!-- The following is initially hidden because of the CSS class -->
<div class="redirect2 hidden">If you aren't redirected, click here</div>
This function replaces the current text with your required text if the redirect was not able to take place.
var count = 10;
var counter = setInterval(timer, 1000);
var output = document.getElementById("displaySeconds");
var container = document.getElementById("container");
function timer() {
count--;
if (count === 0) {
stopTimer();
}
output.innerHTML = count;
};
function stopTimer() {
clearInterval(counter);
window.open("https://www.google.com");
container.innerHTML = ' If you are not redirected to the link Click Here to go to the link.';
}
<div id="container">
You will redirect in <span id="displaySeconds">10</span> seconds.
</div>

Submit button works only once on mobile

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();
});

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 auto scroll rotate using J query

the figures should auto rotate. after completing one cycle, it should start from the previous cycle
$(function() {
var interval = setInterval(function() {
if ($("#div1").scrollTop() != $('#div1')[0].scrollHeight) {
$("#div1").scrollTop($("#div1").scrollTop() + 10);
} else {
clearInterval(interval);
}
}, 1000);
});
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="div1" style="height:60px;width:100%;border:1px solid #ccc;overflow:auto">>
/array to store IDs of our tabs
var tabs = [];
//index for array
var ind = 0;
//store setInterval reference
var inter;
//change tab and highlight current tab title
function change(stringref){
//hide the other tabs
jQuery('.tab:not(#' + stringref + ')').hide();
//show proper tab, catch IE6 bug
if (jQuery.browser.msie && jQuery.browser.version.substr(0,3) == "6.0")
jQuery('.tab#' + stringref).show();
else
jQuery('.tab#' + stringref).fadeIn();
//clear highlight from previous tab title
jQuery('.htabs a:not(#' + stringref + 't)').removeClass('active');
//highlight currenttab title
jQuery('.htabs a[href=#' + stringref + ']').addClass('active');
}
function next(){
//call change to display next tab
change(tabs[ind++]);
//if it's the last tab, clear the index
if(ind >= tabs.length)
ind = 0;
}
jQuery(document).ready(function(){
//store all tabs in array
jQuery(".tab").map(function(){
tabs[ind++] = jQuery(this).attr("id");
})
//set index to next element to fade
ind = 1;
//initialize tabs, display the current tab
jQuery(".tab:not(:first)").hide();
jQuery(".tab:first").show();
//highlight the current tab title
jQuery('#' + tabs[0] + 't').addClass('active');
//handler for clicking on tabs
jQuery(".htabs a").click(function(){
//if tab is clicked, stop rotating
clearInterval(inter);
//store reference to clicked tab
stringref = jQuery(this).attr("href").split('#')[1];
//display referenced tab
change(stringref);
return false;
});
//start rotating tabs
inter = setInterval("next()", 7500);
});

Categories

Resources