I need to execute one function on single click and other function on double click. Problem I am facing is due to the fact that we can not have double click event without first having two single clicks. I want, whenever we have double click then only double click function should execute not single click function . Below is something I have done so far. Please suggest if there is any better way to do it because below code is not always working perfectly.
HTML
<div class='box'>
JS:
var dblclick = false;
//single click function
$('div.box').on('click',function(){
setTimeout(function(){
if(!dblclick){
console.log('singleClick');
}
},200);
});
//resetting double click flag
$('div.box').on('click',function(){
setTimeout(function(){
dblclick = false;
},400);
});
//double click function
$('div.box').on('dblclick',function(){
dblclick = true;
console.log('doubleClick')
});
CSS:
div.box {
height: 100px;
width: 100px;
border: 1px solid black;
}
I think you can do it easily with one timeout, like this:
// where "selector" is your html element selector
var element = $("selector"),
single_click_timeout;
function clicked(e) {
single_click_timeout = setTimeout(function() {
// do something for a SINGLE click
}, 400);
}
function dblclicked(e) {
// stop the single click function
clearTimeout(single_click_timeout);
// do something for a DOUBLE click
}
element.on("click", clicked);
element.on("dblclick", dblclicked);
The trick here is to set a correct amount of time for the setTimeout function. Obviously an user will not perform a double click clicking with an interval of 1 second between clicks, but neither with an interval of 0.01 seconds. So now you've got to try and choose the correct amount of milliseconds for the double click.
check if this works , fiddle demo
$('div.box').prop("disabled", true);
i am using this line to make sure only one is active at a point, also i have kept timeout for click to 1000 ms, you can modify it to what you like.
the js code:
//single click function
$('div.box').on('click',function(){
setTimeout(function(){
if($('div.box').prop("disabled")) return;
console.log('singleClick');
$('div.box').prop("disabled", true);
//some single click work.
$('div.box').prop("disabled", false);
},1000);
});
//double click function
$('div.box').on('dblclick',function(){
if($('div.box').prop("disabled")) return;
$('div.box').prop("disabled", true);
console.log('doubleClick');
//some work then enable single click again
setTimeout(function(){
$('div.box').prop("disabled",false);
},2000);
});
Related
I thought that if I put one click function into click function it was only proceeding the second click function if it was clicked, but when I click the first the codes for second one is running... I thought that if i clicked the second one it should have run the codes.
I mean when I clicked the second one then the codes are visible and doing as they should do, but If click like first function 3 times without to click the second and suddenly click on the second, it is behaving like the codes have run three times.
$(".click1").click(function () {
alert("hej");
$(".click2").
function ({
alert("bye");
});
});
My intention is to only make the second click to run when it is really clicked and not run the codes if I click the first one!
To be more clear. When I click first, it says hej and if I click three time then it will say hej 3x but when I suddenly click click2 it showing bye three times but I only clicked once.
Can anyone explain me why this is happening? and How i can prevent this to happen?
Thanks for the help!
EDIT!!
function click_back() {
current_question_for_answer.splice(0,1);
$("#tillbaka_question").fadeTo("slow", 0.2);
$("#tillbaka_question").off("click");
$(".questions").hide();
$(".containing_boxes").show();
$(".answered_box").remove();
var numbers_of_answered_question = history.length - 1;
for (var i = numbers_of_answered_question; i > -1; i--) {
current_question.push(i);
$(".containing_boxes").prepend('<div class="answered_box">'+i+'</div>');
$("div.containing_boxes > div:nth-child("+history.length+")").css("background-color", "green");
$(".containing_boxes").hide();
$(".containing_boxes").fadeIn(100);
}
$("div.containing_boxes > div").not(":last-child").click(answered_box);
$("div.containing_boxes > div:nth-child("+history.length+")").click(function () {
$("div.containing_boxes > div:nth-child("+history.length+")").click(function () { }) this function should only work if I click it. I can not seperate this code in two new function. If I do it, then the whole system will stop working.....
Because you clicked on click1 3 times, the click event on click2 is 3x created. Thats why it will alert 'bye' 3 times.
You should Unbind click event before binding New click event
$(".click1").click(function () {
alert("hej");
$(".click2").unbind('click');
$(".click2").bind('click',function (){
alert("bye");
});
});
Live Demo
The first click is attaching another click handler which means the second click will fire multiple times, so every time you click it you will get a lot of "bye"s. To avoid this, you can simply set a variable like var isClicked = 0 on load, and then before attaching the handler to click2, check if isClicked == 0, if true then set isClicked = 1 so it only works once
var isClicked = 0;
$(".click1").click(function () {
alert("hej");
if ( isClicked == 0 ) {
isClicked = 1;
$(".click2").
function ({
alert("bye");
});
}
});
I think, his is what you are after:
$(".click1").click(function () { alert("hej"); });
$(".click2").click(function () { alert("bye"); });
Try this:
var click1 = false;
$(".click1").click(function () {
alert("hej");
click1 = true;
});
$(".click2").click(function() {
if (click1 === true) {
alert("bye");
click1 = false;
}
});
Every time you click 1st button, You are registering click event for the 2nd button, so if you click 1st button 5x then 2nd button click event will be registered 5x
The solution is that
You make sure that every time you click 1st button you unregister click event for 2nd button, then register it again
I have an element by clicking on which some function is called by jQuery .click method. There is a condition in the body of the function. When I click on an element one time at a time everything runs smoothly, but if I click two times quickly the condition, which is supposed to stop a function, doesn't run, and the function is executed two times instead of one. So it is as if clicks are being accumulated. How can I prevent this behaviour of a .click method?
$(".collections_pager_right").click(function() {
if (collections_wrapper_left > 0 - collections_wrapper_width + 770) {
$(".collections_slider_wrapper").animate({left: "-=770"}, 400);
};
});
Try to add a attribute like running="false" in your element, so after that you can check it.
$(".collections_pager_right").click(function() {
if($(this).attr('running') == 'false'){
$(this).attr('running','true');
if (collections_wrapper_left > 0 - collections_wrapper_width + 770) {
$(".collections_slider_wrapper").animate({left: "-=770"}, 400, function(){
$(this).attr('running','false');
});
};
}
});
Hi I am working on a click double-click event handler for my jquery ajax engine. The idea is that you can click or double-click a button. I wrote this myself but I don't see why it is not working.
this is the code:
$('body').on('click', '.double-click', function() {
var that = this;
var dblclick = $(that).data('clicks');
if(!dblclick){
dblclick = 0;
}
dblclick = dblclick + 1;
$(that).data('clicks', dblclick);
dblclick = $(that).data('clicks');
console.log('click - ' + dblclick);
if(dblclick > 1){
$(this).data('clicks', 0);
//ajaxloader(this, 1);
alert('dubbel-klik');
console.log('dubbelcik event');
}
setTimeout(function() {
if(dblclick == 1){
$(that).data('clicks', 0);
//ajaxloader(this, 0);
alert('klik');
console.log('single click event');
}
}, 400);
});
It maybe looks a little over complicated but that is because I tried out some stuff. The problem I have is that when I double-click the double click the single click gets also executed. How is this possible when I reset with $(this).data('clicks', 0);. Then the counter has to be 0 and the if statement in the timeout has to be false.
Someone knows what is going wrong!?
O yes see a working demo here: click the click en dubbelclick button
You're overcomplicating this. jQuery has all of this built-in:
$('body').on('click', function(){
alert("single click")
});
$('body').on('dblclick', function(){
alert("double click");
});
This will also click the single though: you might want to check out this thread to see what you could do to prevent that: Javascript with jQuery: Click and double click on same element, different effect, one disables the other
Morning folks. Have an issue with a simple jQuery gallery i'm making. It lets the user cycle through a collection of images via some buttons and at the same time, rotates through these images on a timer. My problem is that the user is able to click the button multiple times which queues up the fade in animation and repeats it over and over, e.g. user clicks button 5 times > same image fades in/out 5 times > gallery moves to next image.
I've tried using:
$('#homeGalleryImage li a').unbind('click');
After the click event is fired and then rebinding:
$('#homeGalleryImage li a').bind('click');
After it's done but this simply removes the click event after pressing a button once and never rebinds to it?
I've also tried disabling the button via:
$('#homeGalleryImage li a').attr('disabled', true);
To no avail... ?
There is a secondary issue where if you manage to click a button while the image is in a transition, the next image appears 'faded' as if the opacity has been lowered? Very strange... Here is the code for button clicks:
var i = 1;
var timerVal = 3000;
$(function () {
$("#homeGalleryControls li a").click(function () {
var image = $(this).data('image');
$('#galleryImage').fadeOut(0, function () {
$('#galleryImage').attr("src", image);
});
$('#galleryImage').fadeIn('slow');
$('.galleryButton').attr("src", "/Content/Images/Design/btn_default.gif");
$(this).find('img').attr("src", "/Content/Images/Design/btn_checked.gif");
i = $(this).data('index') + 1;
if (i == 4) {
i = 0;
}
timerVal = 0;
});
});
Here is the code that cycles through the images on a timer:
//Cycle through gallery images on a timer
window.setInterval(swapImage, timerVal);
function swapImage() {
$('#galleryImage').fadeOut(0, function () {
var imgArray = ["/Content/Images/Design/gallery placeholder.jpg", "/Content/Images/Design/1.jpg", "/Content/Images/Design/2.jpg", "/Content/Images/Design/3.jpg"];
var image = imgArray[i];
i++;
if (i == 4) {
i = 0;
}
$('#galleryImage').attr("src", image);
$('#galleryImage').fadeIn('slow');
});
var currentButton = $('#homeGalleryControls li a img').get(i - 1);
$('.galleryButton').attr("src", "/Content/Images/Design/btn_default.gif");
$(currentButton).attr("src", "/Content/Images/Design/btn_checked.gif");
}
I realise it might be a better idea to use a plugin but I'm very new to jQuery and I'd like to learn something rather than using some ready made code.
Any help at all, is much appreciated.
Thankyou
You could always try adding something to the element to cancel the click event?
For example
$(".element").click(function(e) {
if ( $(this).hasClass("unclickable") ) {
e.preventDefault();
} else {
$(this).addClass("unclickable");
//Your code continues here
//Remember to remove the unclickable class when you want it to run again.
}
}):
In your case you could try adding a check on the click.
$('#homeGalleryImage li a').attr('data-disabled', "disabled");
Then inside your click event
if ( $(this).attr("data-disabled" == "disabled") {
e.preventDefault();
} else {
//Ready to go here
}
Edit
Here is a working example showing the element becoming unclickable. http://jsfiddle.net/FmyFS/2/
if you want to make sure that the registered event is fired only once, you should use jQuery's one :
.one( events [, data ], handler ) Returns: jQuery
Description: Attach a handler to an event for the elements. The handler is executed at most once per element per event type.
see examples:
using jQuery: https://codepen.io/loicjaouen/pen/RwweLVx
// add an even listener that will run only once
$("#click_here_button").one("click", once_callback);
using vanilly JS: https://codepen.io/loicjaouen/pen/gOOBXYq
// add a listener that run only once
button.addEventListener('click', once_callback, {capture: true, once: true});
Does anyone know how to stop this slideshow from 'caching' the amount of clicks through the slides? If I click the arrows 10 times then 10 slides will slide through is there a way to stop this? Or alternatively if you click the opposite arrow for it to cancel the 'cached' clicks from the other?
http://www.switchonthecode.com/tutorials/jquery-creating-a-slideshow
Thanks!
Using the one() function will probably do what you are looking for. Adjust the code to the following:
$(document).ready(function(){
// The "one()" function means that this action is disconnected
// from the element once the action occurs. In other words, click
// it twice, and the second one does nothing.
$("#slideshow-previous").one("click", showPreviousSlide);
$("#slideshow-next").one("click", showNextSlide);
...
});
However just doing that isn't enough. We have to hook up the event handler again after the animation is finished. Use the callback function for animate():
function updateContentHolder()
{
...
$("#slideshow-scroller").animate({scrollLeft: scrollAmount}, 1000, function() {
$("#slideshow-previous").one("click", showPreviousSlide);
$("#slideshow-next").one("click", showNextSlide);
});
}
As was pointed out in the comments this has the problem of attaching showPreviousSlide and showNextSlide multiple times to whichever button was not pressed. You can remedy this by doing just a little more work:
function showPreviousSlide()
{
currentSlide--;
updateContentHolder($(this).attr("id"), showPreviousSlide);
updateButtons();
}
function showNextSlide()
{
currentSlide++;
updateContentHolder($(this).attr("id"), showNextSlide);
updateButtons();
}
...
function updateContentHolder(id, callback)
{
...
$("#slideshow-scroller").animate({scrollLeft: scrollAmount}, 1000, function() {
$("#" + id).one("click", callback);
});
}
You could set a flag to true whenever an arrow is clicked something like isPending. Then check this whenever an arrow is clicked and if it is true, ignore the click. Then when the animation finishes set the flag back to false.