Content Click Counter - javascript

I need to count the number of clicks on a piece of content - after which, I need to run a certain function.
I can't run the function on every click, only after the user finishes their desired clicks.
The amount of clicks needs to be 1, 2, or 3 and above, where I only want to do something on one or two clicks, and ignore anything else.
Note I only need to run the function after the clicks, then reset the counter.
I've tried the following, but it logs 'single' after every click.
var clicks = 0;
$(controller).click(function() {
var elem = this, $elem = jQuery(elem), clicks = $elem.data('clicks') || 0;
clicks += 1;
// Reset triple click counter if no click is made within 500ms
setTimeout(function() {
clicks = 0;
}, 500);
setTimeout(function() {
if (clicks >= 3) {
console.log("triple or more");
}
if (clicks === 2) {
console.log("double");
}
if (clicks === 1) {
console.log("single");
}
}, 200);
});
Here is a JSBin example

It's a little hard to see what you want to happen after 3 clicks, do you want to trigger triple clicks for each of them or not.
I created a version that you might want to look at: http://jsbin.com/dutilojujowa/5/edit
The ideas are:
Save all the click counter data into the data attribute instead of relying on scope - I find that easier.
Throttle your reset counter, otherwise multiple clicks can be handled very strangely
Throttle your action counter, or you might get multiple actions accidentally!
Make sure you set $elem.data('clicks') to 1 at some point, or it won't work.

You need to update $elem.data('clicks') at the end of your function. See http://css-tricks.com/snippets/jquery/triple-click-event/

Can you try following code:
var totalCount;
var intervalVar;
var ShowResultVar;
function HandleClicks() {
totalCount = totalCount + 1;
}
function ShowResult() {
if(totalCount == 0)
{
console.log("No Clicks");
}
else if (totalCount == 1)
{
console.log("One Click");
}
else if(totalCount == 2)
{
console.log("Two Clicks");
}
else if (totalCount >2) {
console.log("Three or more Clicks");
}
}
$(document).ready(function () {
totalCount = 0;
$("#myControl").bind("click", HandleClicks);
intervalVar = setInterval(function () {
totalCount = 0;
}, 500);
ShowResultVar = setInterval(function () {
ShowResult();
}, 200);
});
It is working for me. Output is as follows:
No Clicks
No Clicks
No Clicks
No Clicks
No Clicks
No Clicks
No Clicks
No Clicks
No Clicks
No Clicks
One Click
Two Clicks
One Click
Two Clicks
No Clicks
One Click
Two Clicks
No Clicks
One Click
Two Clicks
Two Clicks
Three or more Clicks
One Click
One Click
No Clicks
No Clicks
No Clicks
No Clicks
No Clicks

Try this-
$("#content").data('clicks', 0);
$("#content").click(function () {
var elem = this,
$elem = jQuery(elem);
var clicks = $elem.data('clicks') + 1
$elem.data('clicks', clicks);
if (clicks == 1) {//start re-setter and counter when first click
setTimeout(function () {
$elem.data('clicks', 0);
}, 500);
setTimeout(function () {
var clicks = $elem.data('clicks');
if (clicks >= 3) {
console.log("triple or more");
}
if (clicks === 2) {
console.log("double");
}
if (clicks === 1) {
console.log("single");
}
}, 200);
}
});
DEMO

Related

Change a global variable from inside an if-function

I have a hotspot image thingy thing where you got spots (called "items") hovering on the image which are clickable. When you click such an item, a textbox appears on the right side of the image with all the information. Now if you click another item, the textbox should close and a new one opens up.
This is the current code:
jQuery(document).ready(function() {
counter = 1;
var lastHotspot = 0;
jQuery("#{{item.item_id}}").click(function(){
if (counter == 1) {
jQuery("#textbox{{item.item_id}}").show();
lastHotspot = {{item.item_id}};
counter++;
} else {
jQuery("#textbox" + lastHotspot).hide();
jQuery("#textbox{{item.item_id}}").show();
lastHotspot = {{item.item_id}};
}
});
});
Because there isn't a textbox the first time everything loads, I want to run the ".show" on the textbox the first time you click an item and then store the item's ID. After that, when I click an item, it should ".hide" the textbox of the previous item, then ".show" the next textbox from the clicked item and then re-assign the item-ID to "lastHotspot" and then repeat everytime an item gets clicked.
The problem I have is, that "lastHotspot" doesnt get stored inside the variable after getting re-assigned inside the if-function, even tho the counter does.
How can I fix this issue?
You can either bind the functions before you attach them to the click events, or you can use a global object to modify the counters:
jQuery(document).ready(function() {
counter = 1;
var lastHotspot = 0;
jQuery("#{{item.item_id}}").click((function(){
if (counter == 1) {
jQuery("#textbox{{item.item_id}}").show();
lastHotspot = {{item.item_id}};
counter++;
} else {
jQuery("#textbox" + lastHotspot).hide();
jQuery("#textbox{{item.item_id}}").show();
lastHotspot = {{item.item_id}};
}
}).bind(this));
});
Using global Object:
jQuery(document).ready(function() {
configs = { counter: 1 };
var lastHotspot = 0;
jQuery("#{{item.item_id}}").click(function(){
if (configs.counter == 1) {
jQuery("#textbox{{item.item_id}}").show();
lastHotspot = {{item.item_id}};
configs.counter++;
} else {
<...>
}
});
});

Prevent actions before setTimeout() is over

Im curently making a memory game and if two card matches it blocks them but if not they should flip back. The problem is that you can click on other cards even if there are two cards already flipped and if you click more cards the game goes crazy and stops working
Any idea?
here's the code
https://codepen.io/stivennpe/pen/KRxvxR?editors=1010
restart ();
bindcards();
// to restart the game and shuffle the cards
function restart() {
$('.restart').on('click', function () {
cards = shuffle($('.card'));
$(".card").each(function() {
$( this ).removeClass( "open match show" );
});
$('.deck').html(cards);
bindcards();
});
}
//to open/show the card
function bindcards(){
$('.card').click(function () {
$(this).addClass('open show');
let openCards = $('.open');
let list = jQuery.makeArray(openCards);
if (list.length === 2 && list[0].innerHTML ===
list[1].innerHTML){
$(openCards).addClass('match');
}
if (list.length === 2) {
setTimeout(hola, 1000)
function hola() {$(openCards).removeClass('open show');
}
}
});
}
thanks
Seems like for a simple solution you could set a global variable, something like blockClicks
If blockClicks is true, do nothing when a user clicks. Reset its value to false after timeout
There is a race condition between applying the .open class to the div element, refreshing the page, querying that element, and the user speeding their way through your game. Instead of adding the .open class to the div, hoping the page refreshes quick enough, then immediately querying against with to find out how many open cards you have, keep a local variable count. Below is the slight modification to your code
function bindcards() {
let numOfOpenCards = 0;
$(".card").click(function(e) {
++numOfOpenCards;
if(numOfOpenCards > 2)
return;
$(this).addClass("open show");
let openCards = $(".open");
let list = jQuery.makeArray(openCards);
if (numOfOpenCards >= 2 && list && list.length >= 2 && list[0].innerHTML === list[1].innerHTML) {
$(openCards).addClass("match");
}
if (numOfOpenCards >= 2) {
setTimeout(hola, 1000);
function hola() {
numOfOpenCards = 0;
let openCards = $(".open");
let list = jQuery.makeArray(openCards);
if(list) {
for(let i = 0; i < list.length; ++i)
$(list[i]).removeClass("open show");
}
}
}
});
}
If two cards are already open, the most recent card check. The previous card check should still complete and refresh as needed.
https://codepen.io/anon/pen/NzPBrB?editors=1010
Additional edit
If you do not want to use numOfOpenCards, you can use the following. Find how many are already open. If there are more than 2 already, just quit. If there are less than already flipped, add the class then query the DOM again. Anywhere numOfCards is used you can replace with list.length;
let openCards = $(".open");
let list = jQuery.makeArray(openCards);
if(list && list.length > 2)
return;
$(this).addClass("open show");
openCards = $(".open");
list = jQuery.makeArray(openCards);
if (list.length >= 2) {
setTimeout(hola, 1000);
function hola() {
$(list).removeClass('open show');
}
}

How to make a function run before a button can be pressed again in JS?

I'm trying to write a program in JavaScript in which certain functions must be performed before a button can be pressed again.
The button performs a function that should only be performed once per turn, but I want other actions to be performed before the next turn, and to have a sort of confirmation before progressing to the next turn. In psuedocode it might look something like this:
buttonFunction();
actionOne();
actionTwo();
turnOverConfirm();
etc.
But I'm not so sure how to do that. Right now the button can be pressed at any time. How do I make it so that the user must confirm before the button can be pressed again?
You can disable and enable buttons via javascript. You could block it like that:
document.getElementById("button").disabled = true
Just set it to false again to make it clickable again!
You can use the javascript confirm function. This function will popup a message box with ok and cancel
Here is an example
var r = confirm("Press a button!");
if (r == true) {
alert("OK was clicked");
} else {
alert("Cancel was clicked");
}
What you can do is when a user clicks on a button, popup a confirm box, then if they click ok you can then run the function you listed above.
There are few ways
You can hide the button till processing is ready or replace with an "please wait..." image
You can create an prevent varaible or remove temporary click event function
var Action = (function(){
var prevent = false;
function _start() {
if (prevent === false) {
prevent = true;
_process();
}
}
function _process() {
// DO Action
prevent = false;
}
return { start: _start }
})();
Fire
you can make event for evry click here is an example with alert and change button color all in one function
var clicked = 0;
var btn = document.getElementById("btn");
function clickBtn(){
if (clicked == 0) {
alert("it's first click");
btn.style.background = "black";
clicked = 1;
}else if (clicked == 1) {
alert("it's second click");
btn.style.background = "orange";
clicked = 2;
} else if (clicked == 2) {
alert("it's third click");
btn.style.background = "green";
clicked = 3;
}
}
#btn{
border-radius:15px 0 15px 0;
color:white;
border:none;
padding:15px;
background:blue;
font-weight:bold;
}
#btn:hover{
border-radius:0 15px 0 15px;
}
<button id="btn" onclick="clickBtn()">Click Me</button>

If statement does not work when condition is met

Here is my code:
var count = 2;
var decrementAmount = 1;
function reduceVariable() {
count -= decrementAmount;
}
$("#button").click(function() {
reduceVariable();
});
if (count == 0) {
$("#avrageReactionTime").html("Hello");
};
When i click my button twice the div that has the id avrageReactionTime does not change to have the text hello. Why do i have this problem...
Right now you test once, instead of testing every time the counter changes.
You must put the if inside the event handler :
$("#button").click(function() {
reduceVariable();
if (count==0) {
$("#avrageReactionTime").html("Hello");
}
});
Note that properly indenting your code makes it obvious.

Can't execute a jQuery function more than once

I have the following function:
$('#edit').on("click", function () {
$('#edit').text('click1');
$('table a').click(function (e) {
e.preventDefault();
});
$('table a').css("cursor", "default");
}
});
$('#edit').click(function () {
$('#edit').unbind();
$('#edit-message-placeholder').empty();
$('#edit').text('click2');
$("table tbody").sortable("disable");
$('table a').unbind()
$('table a').css("cursor", "auto");
});
});
On first click, I want it to change the text of div#edit. On second click, it will change the text to something else. On third click, the function will behave as though it was clicked the first time.
I tried to find a solution online, but found nothing useful.
The problem is that you're approaching this incorrectly. You don't need to bind/unbind event handlers. You only need one event handler that alternates in functionality:
JavaScript
var isOkay = true;
$("p").click(function () {
if (isOkay) {
$(this).text("1st click");
} else {
$(this).text("2nd click");
}
isOkay = !isOkay;
})
HTML
<p>Click me!</p>
Every time the <p> is clicked, it performs an action and then switches the value of a boolean variable, isOkay. This means that it will alternate between the if and else block. Note that the isOkay variable is held outside the scope of the $("p").click(...) event handler.
fiddle
Try this -
Use the data property to temporarily save the counter data
<button id="edit" data-count="1">1</button>
function doWork(val){
alert(val);
};
$('#edit').on("click", function () {
if($(this).data('count') == ""){
$(this).data('count') = 1;
}
var count = parseInt($(this).data('count'));
if (count == 1){
doWork(count);
}else if (count == 2){
doWork(count);
}else if (count == 3){
doWork(count);
}
count += 1
count = count >= 4 ? 1: count;
$(this).data('count', count);
$(this).html($(this).data('count'));
});
Here is the jsfiddle - http://jsfiddle.net/pt3zE/1/

Categories

Resources