Registering jQuery click, first and second click - javascript

Is there a way to run two functions similar to this:
$('.myClass').click(
function() {
// First click
},
function() {
// Second click
}
);
I want to use a basic toggle event, but .toggle() has been deprecated.

Try this:
$('.myClass').click(function() {
var clicks = $(this).data('clicks');
if (clicks) {
// odd clicks
} else {
// even clicks
}
$(this).data("clicks", !clicks);
});
This is based on an already answered question: Alternative to jQuery's .toggle() method that supports eventData?

Or this :
var clicks = 0;
$('.myClass').click(function() {
if (clicks == 0){
// first click
} else{
// second click
}
++clicks;
});

this I worked for my menu
var SubMenuH = $('.subBoxHederMenu').height();
var clicks = 0;
$('.btn-menu').click(function(){
if(clicks == 0){
$('.headerMenu').animate({height:SubMenuH});
clicks++;
console.log("abierto");
}else{
$('.headerMenu').animate({height:"55px"});
clicks--;
console.log("cerrado");
}
console.log(clicks);
});

i don't know what you are tryin to do but we can get basic toggle by
$('.myClass').click({
var $this=$(this);
if($this.is(':hidden'))
{
$this.show('slow');
}else{
$this.hide('slow');
}
})
note: this works for endless click event for that element .. not just for two clicks (if that is what you want)
OR you can use css class to hide/show the div and use jquery.toggleClass()

In the method mentioned below We are passing an array of functions to our custom .toggleClick() function. And We are using data-* attribute of HTML5 to store index of the function that will be executed in next iteration of click event handling process. This value, stored in data-index property, is updated in each iteration so that we can track the index of function to be executed in next iteration.
All of these functions will be executed one by one in each iteration of click event. For example in first iteration function at index[0] will be executed, in 2nd iteration function stored at index[1] will be executed and so on.
You can pass only 2 functions to this array in your case. But this method is not limited to only 2 functions. You can pass 3, 4, 5 or more functions in this array and they will be executed without making any changes in code.
Example in the snippet below is handling four functions. You can pass functions according to your own needs.
$.fn.toggleClick = function(funcArray) {
return this.click(function() {
var elem = $(this);
var index = elem.data('index') || 0;
funcArray[index]();
elem.data('index', (index + 1) % funcArray.length);
});
};
$('.btn').toggleClick([
function() {
alert('From Function 1');
}, function() {
alert('From Function 2');
}, function() {
alert('From Function 3');
}, function() {
alert('From Function 4');
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button type="button" class="btn">Click Me</button>
<button type="button" class="btn">Click Me</button>

If you literally only want the first and second click:
$('.myClass').one( 'click', function() {
// First click
$('.myClass').one( 'click', function() {
// Second click
});
);

var click_s=0;
$('#show_pass').click(function(){
if(click_s % 2 == 0){
$('#pwd').attr('type','text');
$(this).html('Hide');
}
else{
$('#pwd').attr('type','password');
$(this).html('Show');
}
click_s++;
});

When You click the selector it automatically triggers second and waiting for another click event.
$(selector).click(function(e){
e.preventDefault(); // prevent from Posting or page loading
//do your stuff for first click;
$(this).click(function(e){
e.preventDefault();// prevent from Posting or page loading
// do your stuff for second click;
});
});
I hope this was helpful to you..

I reach here looking for some answers, and thanks to you guys I´ve solved this in great manner I would like to share mi solution.
I only use addClass, removeClass and hasClass JQuery commands.
This is how I´ve done it and it works great:
$('.toggle').click(function() {
if($('.categ').hasClass("open")){
$('.categ').removeClass('open');
}
else{
$('.categ').addClass('open');
}
});
This way a class .open is added to the Html when you first clikc.
Second click checks if the class exists. If exists it removes it.

Related

automatically clicking a button in javascript

I have this button:
<button class="btn btn-primary" type="button">Display</button>
and I'd like to click automatically that button every 100ms, I wrote this script but it doesnt work:
window.onload = function(){
var button=document.getElementsByClassName("btn btn-primary");
setInterval(function(){
button.click();
}, 100);
)
getElementsByClassName return a NodeList instead of an Element. Try to use querySelector
window.addEventListener('load', function () {
var button = document.querySelector(".btn.btn-primary");
setInterval(function () {
button.click();
}, 100);
});
If you want apply with all matched buttons, you can use querySelectorAll and [].slice.call to convert NodeList to Array
window.addEventListener('load', function () {
var buttonList = document.querySelectorAll(".btn.btn-primary");
var buttons = [].slice.call(buttonList);
setInterval(function () {
buttons.forEach(function (button) {
button.click();
});
}, 100);
});
For making a button click automatically, it is better to pass the function in setInterval Method.
setInterval(function(){
alert('Working fine'); //Same function as it was supposed on click
}, 5000);
To see the working model, I have attached a JS Fiddle to it.
https://jsfiddle.net/xrefwqcj/2/
Many selectors can yield multiple results, so you must specify an index to work with a selected element. If there is only one result the index will be [0].
window.onload = function(){
var button=document.getElementsByClassName('btn btn-primary')[0];
setInterval(function(){
button.click();
}, 100);
}
Also if this script runs before your button has loaded, the selector will not yield any results and could produce an error - here is one solution for that:
window.onload = function(){
setInterval(function(){
if (typeof document.getElementsByClassName('btn btn-primary')[0]!="undefined"){
document.getElementsByClassName('btn btn-primary')[0].click();
}
}, 100);
}
The above script will repeatedly check whether the selected element is defined before clicking it (then continue to do so indefinitely since you don't have any mechanism to toggle it off). You also had a ")" at the last line of your sample code which I think should have been a "}".

jQuery preventing click event to be executed in case of double or multiple clicks by user

I have some code in which I want to stop user from clicking a button multiple times. I have tried multiple things including disabling button on click and enabling it at the end but nothing is working perfectly.
I want to stop "click" event of jQuery (single click) from being executed in case user has clicked on it two or more times.
This is my js fiddle: https://jsfiddle.net/tm5xvtc1/6/
<p id="clickable">Click on this paragraph.</p>
<p id="main">
I will change on clicking
</p>
$("#clickable").click(function(){
$('#main').text('Single click');
});
$("#clickable").dblclick(function(){
$('#main').text('Double click')
});
If i try double clicking, the behavior is:
Single click gets executed first => Then double click gets executed.
I want to prevent single click event to be executed in case user clicks on button multiple times. Suggestions?
According to the jquery documentation:
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.
That being said, you can accomplish what you want by using $('#main').addClass('clicked-once'); and testing for the existence of that class before executing the code inside the single click handler.
$("#clickable").click(function(){
if($(this).hasClass('clicked-once')){
return false;
} else {
$(this).addClass('clicked-once');
$('#main').text('Single click');
}
});
$("#clickable").dblclick(function(){
$('#main').text('Double click')
});
jsfiddle: https://jsfiddle.net/nbj1s74L/
This is bit tricky. You need to calculate the time taken for double click and trigger events. Try the below code
$(function() {
var clicks = 0;
var timer = null;
$("#clickable").on("click", function(e) {
clicks++; // Increment click counter
if (clicks === 1) {
timer = setTimeout(function() {
$('#main').text('Single click');
clicks = 0; //Reset
}, 800); // Increase or decrease if there is slowness or speed
} else {
clearTimeout(timer); //prevent single-click action
$('#main').text('Double click')
clicks = 0; // Reset
}
});
$("#clickable").on("dblclick", function(e) {
e.preventDefault(); //Prevent double click
});
});
Demo : https://jsfiddle.net/cthangaraja/e9e50jht/2/
I found the answer for this.
$(document).on('click', '#clickable', function () {
$(this).prop('disabled', true);
//LOGIC
setTimeout(function () { $(this).prop('disabled', false); }, 500);
});
Its working for me. The set timeout for 500ms doesn't allow code to be re-entrant which is working fine for me at various network/device speeds.
Slight change in the answer given by maverick.
In the set timeout method, reference of this is changed. Hence the code should be changed to:
$(document).on('click', '#clickable', function () {
var self = this;
$(this).prop('disabled', true);
//LOGIC
setTimeout(function () { $(self).prop('disabled', false); }, 500);
});
window.numOfClicks = 0
$("#clickable").click(function(){
window.numOfClicks += 1;
//rest of code
});
Record the number of clicks to use for your functions, example:
if (window.numOfClicks > 1){ //do this}
If you need it reset just put a timeout in the .click()
var resetClicks = function(){ window.numOfClicks = 0 }
$("#clickable").click(function(){
//your other code
setTimeout(resetClicks,5000); //reset every 5 seconds
});

OR condition for running function

I have button (".moreAlertsBtn") that run function when user click on it
I would like to run the same function if user click on another button that contain the id "#alertsBtn"
how do I add OR condition?
$(document).on('click','.moreAlertsBtn',function() { }
also - inside the function, can i add contision if user click on the first button and another if he click on the second?
Just separate them using comma(,) like this:
$(document).on('click','.moreAlertsBtn, #alertsBtn',function() { });
can i add condition if user click on the first button and another if
he click on the second?
$(document)
.on('click','.moreAlertsBtn, #alertsBtn',function() {
if($(this).hasClass('moreAlertsBtn')) {
//.moreAlertsBtn clicked
} else {
//#alertsBtn clicked
}
});
how do I add OR condition?
You can use the comma, which in CSS is "or" (but keep reading):
$(document).on('click','.moreAlertsBtn, #alertsBtn',function() { });
But:
also - inside the function, can i add contision if user click on the first button and another if he click on the second?
If you're going to do that, then it makes more sense to use separate handlers:
$(document).on('click','.moreAlertsBtn',function() { });
$(document).on('click','#alertsBtn',function() { });
But answering the question, yes, you can tell like this:
if (this.id === "alertsBtn") {
// It's #alertsBtn
} else {
// Must be .moreAlertsBtn
}
E.g.:
$(document).on('click','.moreAlertsBtn, #alertsBtn',function() {
if (this.id === "alertsBtn") {
// It's #alertsBtn
} else {
// Must be .moreAlertsBtn
}
});
That works because jQuery will call your handler with this referring to the DOM element you "hooked" the event on (even when you're actually doing delegation, as you are in your examples).
You can use comma in-between selectors as follows :
$(document).on('click','.moreAlertsBtn,#alertsBtn',function() { }

How Store and Disable Event of another element Temporary

I am looking for a way to manage the events. I have a hover function for element A, and click function for element B. I want to disable A`s hover function temporary while the second click of B.
I am looking for a way that not necessary to rewrite the hole function of A inside of B. Something very simply just like "Store and Disable Event, Call Stored Function"
I found some technique like .data('events') and console.log. I tired but failed, or maybe I wrote them in a wrong way.
Please help and advice!
$(A).hover();
$(b).click(
if($.hasData($(A)[0])){ // if A has event,
//STORE all the event A has, and disable
}else{
//ENABLE the stored event for A
}
);
Try this
var hoverme = function() {
alert('Hover Event Fired');
};
$('.A').hover(hoverme);
var i = 0;
$('.B').on('click', function(){
if(i%2 === 0){
// Unbind event
$('.A').off('hover');
}
else{
// Else bind the event
$('.A').hover(hoverme);
}
i++;
});
Check Fiddle
I think that what you want to do is something like this (example for JQuery 1.7.2):
$("#a").hover(function(){alert("test")});
$("#a")[0].active=true;
$("#b").click(function(){
if($("#a")[0].active){
$("#a")[0].storedEvents = [];
var hoverEvents = $("#a").data("events").mouseover;
jQuery.each(hoverEvents , function(key,handlerObj) {
$("#a")[0].storedEvents.push(handlerObj.handler);
});
$("#a").off('hover');
}else{
for(var i=0;i<$("#a")[0].storedEvents.length;i++){
$("#a").hover($("#a")[0].storedEvents[i]);
}
}
$("#a")[0].active = ($("#a")[0].active)==false;
});​
JSFiddle Example
But there are a couple of things that you must have in consideration:
This will only work if you add the events with JQuery, because JQuery keeps an internal track of the event handlers that have been added.
Each version of JQuery handles data("events") differently, that means that this code may not work with other version of JQuery.
I hope that this helps.
EDIT:
data("events") was an internal undocumented data structure used in JQuery 1.6 and JQUery 1.7, but it has been removed in JQuery 1.8. So in JQuery 1.8 the only way to access the events data is through: $._data(element, "events"). But keep in mind the advice from the JQuery documentation: this is not a supported public interface; the actual data structures may change incompatibly from version to version.
You could try having a variable that is outside the scope of functions a and b, and use that variable to trigger the action to take in function b on function a.
var state;
var a = function() {
if(!state) {
state = true;
// Add hover action and other prep. I'd create a third function to handle this.
console.log(state);
};
var b = function() {
if(state) {
state = false;
// Do unbinding of hover code with third function.
} else {
state = true;
// Do whatever else you needed to do
}
}
Without knowing more about what you're trying to do, I'd try something similar to this.
It sounds like you want to disable the click hover event for A if B is clicked.
$("body").on("hover", "#a", function(){
alert("hovering");
});
$("#b").click( function(){
$("body").off("hover", "#a", function() {
alert("removed hovering");
});
});
You can use the jQuery off method, have a look at this fiddle. http://jsfiddle.net/nKLwK/1/
Define a function to assign to hover on A element, so in b click, call unbind('hover') for A element and in second click on b element define again a function to hover, like this:
function aHover(eventObject) {
// Todo when the mouse enter object. You can use $(this) here
}
function aHoverOut(eventObject) {
// Todo when the mouse leave the object. You can use $(this) here
}
$(A).hover(aHover, aHoverOut);
// ...
$(b).click(function(eventObject) {
if($.hasData($(A)[0])){ // if A has event,
$(A).unbind('mouseenter mouseleave'); // This is because not a event hover, jQuery convert the element.hover(hoverIn, hoverOut) in element.bind('mouseenter', hoverIn) and element.bind('mouseleave', hoverOut)
}else{
$(A).hover(aHover, aHoverOut);
}
});
There are provably better ways to do it, but this works fine, on document ready do this:
$("#a")[0].active=false;
$("#b").click(function(){
$("#a")[0].active = ($("#a")[0].active)==false;
if($("#a")[0].active){
$("#a").hover(function(){alert("test")});
}else{
$("#a").off('hover');
}
});
JSFiddle example
You can use .off function from jQuery to unbind the hover on your "a" element.
function hoverA() {
alert('I\'m on hover');
}
$('#a').hover( hoverA );
var active = true;
$('#b').on('click', function(){
if(active){
$('#a').off('hover');
active = false;
} else{
$('#a').hover(hoverA);
active = true;
}
});
Live demo available here : http://codepen.io/joe/pen/wblpC

How to call a function with jQuery blur UNLESS clicking on a link?

I have a small jQuery script:
$('.field').blur(function() {
$(this).next().children().hide();
});
The children that is hidden contains some links. This makes it impossible to click the links (because they get hidden). What is an appropriate solution to this?
This is as close as I have got:
$('.field').blur(function() {
$('*').not('.adress').click(function(e) {
foo = $(this).data('events').click;
if(foo.length <= 1) {
// $(this).next('.spacer').children().removeClass("visible");
}
$(this).unbind(e);
});
});
The uncommented line is suppose to refer to the field that is blurred, but it doesn't seem to work. Any suggestions?
You can give it a slight delay, like this:
$('.field').blur(function() {
var kids = $(this).next().children();
setTimeout(function() { kids.hide(); }, 10);
});
This gives you time to click before those child links go away.
This is how I ended up doing it:
var curFocus;
$(document).delegate('*','mousedown', function(){
if ((this != curFocus) && // don't bother if this was the previous active element
($(curFocus).is('.field')) && // if it was a .field that was blurred
!($(this).is('.adress'))
) {
$('.' + $(curFocus).attr("id")).removeClass("visible"); // take action based on the blurred element
}
curFocus = this; // log the newly focussed element for the next event
});
I believe you can use .not('a') in this situation:
$('.field').not('a').blur(function() {
$(this).next().children().hide();
});
This isn't tested, so I am not sure if this will work or not.

Categories