Javascript: more functions on one click button.Click counter - javascript

I was trying to make more functions on one click button. I am trying to detect how much the user is clicking. If the user clicks onetime: do something, If the user clicks second time: do something. if the user clicks for the third time: do something. But my code is not working at all. can someone tell me what is going on?
var ButtonClickEen = document.getElementById("buttonEen");
var ButtonClickTwee = document.getElementById('buttonTwee');
var clicks = 0;
buttonC.onclick = function(event){
clicks += 1;
};
if (clicks === 1) {
/* 1st click, Do something */
} if (clicks === 2) {
/* 2nd click, Do something else */
};

You have many script errors, starting with selection of elements from DOM at beginning, but main error is your click event function, which has to look like this:
var buttonC = document.getElementById("buttonC");
var clicks = 0;
buttonC.onclick = function(event){
clicks += 1;
if (clicks == 1) {
alert('Click 1');
} else if (clicks == 2) {
alert('Click 2');
} else {
alert('Click 3 or more');
};
};

Related

Supress on click event in react

This is an on-click function for the identifier button. This function will trigger a popup design function when the user clicks on some feature on the map. I want this click functionality on that feature to be suppressed when the user clicks the identifier button a second time. This means the identifier button should act like a start-stop switch.
This function is inside useEffect() and the #IdentifierClick is the id for the button which is in return{} part which will trigger the click event.
const IdentifierClick = () => {
console.log("working");
// clicktimes = clicktimes+1;
// console.log("Button click times ",clicktimes)
if((enableIdentify == false))
{
initialMap.on('singleclick', function (evt)
{
console.log(evt, "printevt");
var myLayerChecked;
console.log(layerlist, "printlayerlist");
for (let i = 0; i <= 4; i++)
{
layerlist[1].values_.layers.array_[i].values_.layers.array_.forEach(arrayItem => {
myLayerChecked = arrayItem.state_.visible;
console.log("myLayerChecked", myLayerChecked);
// console.log(layerlists,"printlayerlist");
if (myLayerChecked == true) {
document.getElementById('popup-content').innerHTML = '<p class="identifier_p"><b>Identifier Details</b></p>';
console.log("My Array Data", arrayItem.values_.source)
designHtml(evt, arrayItem.values_.source, arrayItem.values_.title);
enableIdentify = true;
}
else
{
console.log("No Layer is checked");
}
});
}
})
}
else {
}
});
The intialMap.on('singleclick',function()) should be enabled and disabled by IdentifierClick function when we click to trigger the function. Please help me achieve this task.

Element disappearing before it is supposed to

Recently I've been coding a clicker game and now have run into a problem with the onclick function. What I'm trying to do is on the first click, have it change into certain text, and on the second and third clicks change it to a different text. However, on the fourth click, I'd like it to disappear.
However, it disappears on the third click instead of the fourth click. The third click is supposed to show more text, and then call a function and vamoose. It just disappears. Here is my code:
function change_text(){
let first_click = true;
onclick = function() {
if (first_click) {
document.getElementById("speech").innerHTML = "You will? Thanks so much! Let's make our first pastry. Click the pastry!";
first_click = false;
}
else {
document.getElementById("speech").innerHTML = "Wow, that looks amazing! It make take a while to bake them all by hand; so when you want to go faster, head to the shop and buy upgrades! Have fun!";
function second_click(){
document.getElementById("speech").outerHTML = ""
}
document.getElementById("speech").onclick = second_click();
}
}
What can I do?
I'm going to rewrite your code because it seems to be missing something.
In this code, I'm using a single event handler. Then using a counter and switch statement to determine the current click count.
let speech = document.querySelector("#speech");
let clicks = 1;
speech.addEventListener("click",function(){
speech.style.display = "block";
switch(clicks){
case 1: speech.innerHTML = "You will? Thanks so much! Let's make our first pastry. Click the pastry!";break;
case 2: speech.innerHTML = "Wow, that looks amazing! It make take a while to bake them all by hand; so when you want to go faster, head to the shop and buy upgrades! Have fun!";break;
case 3: speech.innerHTML = "3 text!!";break;
case 4: speech.innerHTML = "";speech.style.display = "none";clicks=0;break;
}
clicks++;
});
#speech{background:red;cursor:pointer;}
<div id="speech">CLICK HERE</div>
Try something like that.
var clicks = 0;
function change_text(){
clicks += 1;
console.log("Action " +clicks)
if (clicks === 1) {
//do something
} else if (clicks === 2) {
//do something
} else if (clicks === 3) {
//do something
} else if (clicks === 4) {
//do something
}
}
<button onclick="change_text()">Click me</button>
Your code is difficult to understand. Just an advice, try to organize your logic before write code and try to code in a simple way like this:
const speeches = ["You will? Thanks so much! Let's make our first pastry. Click the pastry!'", "Wow, that looks amazing! It make take a while to bake them all by hand; so when you want to go faster, head to the shop and buy upgrades! Have fun!", "Third speech"];
const speech = document.getElementById("speech");
let clickCounter = 0;
speech.addEventListener("click", function() {
if (clickCounter >= speeches.length) {
clickCounter = 0;
speech.style.display = 'none';
return;
}
speech.innerHTML = speeches[clickCounter];
clickCounter++;
});
<div id="speech">CLICK ME!</div>

Jquery If Else Statement Issue

I have multiple buttons and when I click each one I want an element associated with that button to slide down and then when I click the same button the same element slides back up. The code below works but if I click one button it slides down then I click the second button nothing happens because it runs the else if part of the code. How would I fix this?
var moreOption = 1;
$(".more-button").click(function(){
var buttonNumber = $(this).attr('buttonNumber');
if (moreOption === 1) {
$("#more"+buttonNumber).slideDown();
moreOption = 2;
} else if (moreOption === 2) {
$("#more"+buttonNumber).slideUp();
moreOption = 1;
}
});
Just use a data-attribute on the button and switch the state manually like this:
<button class="more-button" data-showMore="1" data-buttonNumber="1"/>
$(".more-button").click(function(){
var buttonNumber = $(this).data('buttonNumber');
var moreOption = $(this).data('showMore');
if (moreOption == '1') {
$("#more"+buttonNumber).slideDown();
$(this).data('showMore', '2');
} else if (moreOption == '2') {
$("#more"+buttonNumber).slideUp();
$(this).data('showMore', '1');
}
});

Stop single click event when double-clicking? [duplicate]

Is there something in jquery that would allow me to differentiate between behavior on double click and single click?
When I bind both to same element only the single click gets executed.
Is there a way that wait for some time before execution of the single click to see if the user clicks again or not?
Thanks :)
I found that John Strickler's answer did not quite do what I was expecting. Once the alert is triggered by a second click within the two-second window, every subsequent click triggers another alert until you wait two seconds before clicking again. So with John's code, a triple click acts as two double clicks where I would expect it to act like a double click followed by a single click.
I have reworked his solution to function in this way and to flow in a way my mind can better comprehend. I dropped the delay down from 2000 to 700 to better simulate what I would feel to be a normal sensitivity. Here's the fiddle: http://jsfiddle.net/KpCwN/4/.
Thanks for the foundation, John. I hope this alternate version is useful to others.
var DELAY = 700, clicks = 0, timer = null;
$(function(){
$("a").on("click", function(e){
clicks++; //count clicks
if(clicks === 1) {
timer = setTimeout(function() {
alert("Single Click"); //perform single-click action
clicks = 0; //after action performed, reset counter
}, DELAY);
} else {
clearTimeout(timer); //prevent single-click action
alert("Double Click"); //perform double-click action
clicks = 0; //after action performed, reset counter
}
})
.on("dblclick", function(e){
e.preventDefault(); //cancel system double-click event
});
});
The solution given from "Nott Responding" seems to fire both events, click and dblclick when doubleclicked. However I think it points in the right direction.
I did a small change, this is the result :
$("#clickMe").click(function (e) {
var $this = $(this);
if ($this.hasClass('clicked')){
$this.removeClass('clicked');
alert("Double click");
//here is your code for double click
}else{
$this.addClass('clicked');
setTimeout(function() {
if ($this.hasClass('clicked')){
$this.removeClass('clicked');
alert("Just one click!");
//your code for single click
}
}, 500);
}
});
Try it
http://jsfiddle.net/calterras/xmmo3esg/
Sure, bind two handlers, one to click and the other to dblclick. Create a variable that increments on every click. then resets after a set delay. Inside the setTimeout function you can do something...
var DELAY = 2000,
clicks = 0,
timer = null;
$('a').bind({
click: function(e) {
clearTimeout(timer);
timer = setTimeout(function() {
clicks = 0;
}, DELAY);
if(clicks === 1) {
alert(clicks);
//do something here
clicks = 0;
}
//Increment clicks
clicks++;
},
dblclick: function(e) {
e.preventDefault(); //don't do anything
}
});
You could probably write your own custom implementation of click/dblclick to have it wait for an extra click. I don't see anything in the core jQuery functions that would help you achieve this.
Quote from .dblclick() at the jQuery site
It is inadvisable to bind handlers to both the click and dblclick events for the same element. The sequence of events triggered varies from browser to browser, with some receiving two click events before the dblclick and others only one. Double-click sensitivity (maximum time between clicks that is detected as a double click) can vary by operating system and browser, and is often user-configurable.
Look at the following code
$("#clickMe").click(function (e) {
var $this = $(this);
if ($this.hasClass('clicked')){
alert("Double click");
//here is your code for double click
return;
}else{
$this.addClass('clicked');
//your code for single click
setTimeout(function() {
$this.removeClass('clicked'); },500);
}//end of else
});
Demo goes here http://jsfiddle.net/cB484/
I've written a jQuery plugin that allow also to delegate the click and dblclick events
// jQuery plugin to bind both single and double click to objects
// parameter 'delegateSelector' is optional and allow to delegate the events
// parameter 'dblclickWait' is optional default is 300
(function($) {
$.fn.multipleClicks = function(delegateSelector, clickFun, dblclickFun, dblclickWait) {
var obj;
if (typeof(delegateSelector)==='function' && typeof(clickFun)==='function') {
dblclickWait = dblclickFun; dblclickFun = clickFun; clickFun = delegateSelector; delegateSelector = null; // If 'delegateSelector' is missing reorder arguments
} else if (!(typeof(delegateSelector)==='string' && typeof(clickFun)==='function' && typeof(dblclickFun)==='function')) {
return false;
}
return $(this).each(function() {
$(this).on('click', delegateSelector, function(event) {
var self = this;
clicks = ($(self).data('clicks') || 0)+1;
$(self).data('clicks', clicks);
if (clicks == 1) {
setTimeout(function(){
if ($(self).data('clicks') == 1) {
clickFun.call(self, event); // Single click action
} else {
dblclickFun.call(self, event); // Double click action
}
$(self).data('clicks', 0);
}, dblclickWait || 300);
}
});
});
};
})(jQuery);
This solution works for me
var DELAY = 250, clicks = 0, timer = null;
$(".fc-event").click(function(e) {
if (timer == null) {
timer = setTimeout(function() {
clicks = 0;
timer = null;
// single click code
}, DELAY);
}
if(clicks === 1) {
clearTimeout(timer);
timer = null;
clicks = -1;
// double click code
}
clicks++;
});
i am implementing this simple solution , http://jsfiddle.net/533135/VHkLR/5/
html code
<p>Click on this paragraph.</p>
<b> </b>
script code
var dbclick=false;
$("p").click(function(){
setTimeout(function(){
if(dbclick ==false){
$("b").html("clicked")
}
},200)
}).dblclick(function(){
dbclick = true
$("b").html("dbclicked")
setTimeout(function(){
dbclick = false
},300)
});
its not much laggy
var singleClickTimer = 0; //define a var to hold timer event in parent scope
jqueryElem.click(function(e){ //using jquery click handler
if (e.detail == 1) { //ensure this is the first click
singleClickTimer = setTimeout(function(){ //create a timer
alert('single'); //run your single click code
},250); //250 or 1/4th second is about right
}
});
jqueryElem.dblclick(function(e){ //using jquery dblclick handler
clearTimeout(singleClickTimer); //cancel the single click
alert('double'); //run your double click code
});
I made some changes to the above answers here which still works great: http://jsfiddle.net/arondraper/R8cDR/
Below is my simple approach to the issue.
JQuery function:
jQuery.fn.trackClicks = function () {
if ($(this).attr("data-clicks") === undefined) $(this).attr("data-clicks", 0);
var timer;
$(this).click(function () {
$(this).attr("data-clicks", parseInt($(this).attr("data-clicks")) + 1);
if (timer) clearTimeout(timer);
var item = $(this);
timer = setTimeout(function() {
item.attr("data-clicks", 0);
}, 1000);
});
}
Implementation:
$(function () {
$("a").trackClicks();
$("a").click(function () {
if ($(this).attr("data-clicks") === "2") {
// Double clicked
}
});
});
Inspect the clicked element in Firefox/Chrome to see data-clicks go up and down as you click, adjust time (1000) to suit.
(function($){
$.click2 = function (elm, o){
this.ao = o;
var DELAY = 700, clicks = 0;
var timer = null;
var self = this;
$(elm).on('click', function(e){
clicks++;
if(clicks === 1){
timer = setTimeout(function(){
self.ao.click(e);
}, DELAY);
} else {
clearTimeout(timer);
self.ao.dblclick(e);
}
}).on('dblclick', function(e){
e.preventDefault();
});
};
$.click2.defaults = { click: function(e){}, dblclick: function(e){} };
$.fn.click2 = function(o){
o = $.extend({},$.click2.defaults, o);
this.each(function(){ new $.click2(this, o); });
return this;
};
})(jQuery);
And finally we use as.
$("a").click2({
click : function(e){
var cid = $(this).data('cid');
console.log("Click : "+cid);
},
dblclick : function(e){
var cid = $(this).data('cid');
console.log("Double Click : "+cid);
}
});
Same as the above answer but allows for triple click. (Delay 500)
http://jsfiddle.net/luenwarneke/rV78Y/1/
var DELAY = 500,
clicks = 0,
timer = null;
$(document).ready(function() {
$("a")
.on("click", function(e){
clicks++; //count clicks
timer = setTimeout(function() {
if(clicks === 1) {
alert('Single Click'); //perform single-click action
} else if(clicks === 2) {
alert('Double Click'); //perform single-click action
} else if(clicks >= 3) {
alert('Triple Click'); //perform Triple-click action
}
clearTimeout(timer);
clicks = 0; //after action performed, reset counter
}, DELAY);
})
.on("dblclick", function(e){
e.preventDefault(); //cancel system double-click event
});
});
This is a method you can do using the basic JavaScript, which is works for me:
var v_Result;
function OneClick() {
v_Result = false;
window.setTimeout(OneClick_Nei, 500)
function OneClick_Nei() {
if (v_Result != false) return;
alert("single click");
}
}
function TwoClick() {
v_Result = true;
alert("double click");
}
If you don't want to create separate variables to manage the state, you can check this answer https://stackoverflow.com/a/65620562/4437468

Adding keyboard shortcuts (up, down, enter) to search input suggestions div

I have a search suggestion div that appears when you keyUp an input. This works fine, but now I am trying to make keyboard shortcuts in action.
I want a behavior like when you click down keyboard arrow button a span gets selected and if it is selected then another span that is after gets selected, similarly, if you click up arrow an upward span gets selected, when you click enter then link opens.
I am stuck because I could not remove a:hover and could not add classes to it. Even after I have basically no idea how to do it. But I really tried hard and a lot..
Here is a jsfiddle link (type anything in field). maybe somebody will help me.
This code should go when the request is made and data is being returned:
<script type="text/javascript">
$(document).ready(function(){
total = 3;
$(".result-item").mouseenter(
function(){
hovered = $(this).attr("id");
total = 3;
$(".result-item").each(function(){
$(this).children("a").css({
'background-color':'#e4e4e4',
'color':'#000000'
});
$(this).find(".searchheading").css({
'color':'#191919'
});
$(this).find(".searchcaption").css({
'color':'#555555'
});
});
$(this).children("a").css({
'background-color':'#b7b7b7',
'color':'#ffffff'
});
$(this).find(".searchheading").css({
'color':'#ffffff'
});
$(this).find(".searchcaption").css({
'color':'#f1f1f1'
});
}
);
});
</script>
And this code on a page where request is made:
$("#suggestions").hide();
$("#search").bind('keyup', function(event){
if (event.which == 40 || event.which == 38 || event.which == 13) return false;
else
{
hovered = undefined;
lookup($(this).val());
}
});
$("#search").bind('keydown', 'down', function(evt){
if ($("#suggestions").is(":visible"))
{
if (typeof hovered == 'undefined')
{
$("#result-item-0").trigger("mouseenter");
return;
}
count = parseInt($("#"+hovered).attr("count"));
next = (count + 1);
if (next == total)
next = 0;
$("#result-item-"+next).trigger("mouseenter");
}
});
$("#search").bind('keydown', 'up', function(evt){
if ($("#suggestions").is(":visible"))
{
if (typeof hovered == 'undefined')
{
$("#result-item-"+(total-1)).trigger("mouseenter");
return;
}
count = parseInt($("#"+hovered).attr("count"));
prev = (count - 1);
if (prev == -1)
prev = (total-1);
$("#result-item-"+prev).trigger("mouseenter");
}
});
$("#search").bind('keydown', 'return', function(evt){
if ($("#suggestions").is(":visible"))
{
if (typeof hovered == 'undefined')
{
str = $("#search").val();
window.location.href = urlencode(str); // urlencode is a custom function
return false;
}
count = parseInt($("#"+hovered).attr("count"));
current = count;
$("#result-item-"+current).trigger("mouseenter");
$("#suggestions").fadeOut();
window.location.href = $("#"+hovered).children("a").attr("href");
}
});
})
;
Also I removed onkeyup="" attribute on element, this approach is nicer.

Categories