Simulate div click multiple times - javascript

I've got slider in template glitching, and code is minimized. So, got tired of looking for the cause of the problem and decided to use a quick hack.
I need to fire a div click multiple times.
I've used this piece of code to trigger a click
$('.control-prev').trigger('click');
Works fine for one time click.
Now, how do i make it click multiple times?

http://jsfiddle.net/br4Lmyso/ (warning: creates three alerts, just to quickly show it works)
// set your count to whatever you want. Get a reference to the div
// so you're not querying the DOM everytime.
var triggerCount = 3;
var triggerDiv = $('.control-prev');
// loop!
for(var i = 0; i < triggerCount; i++) {
triggerDiv.trigger('click');
}

To be clear, trigger(...) does not simulate the click behavior and there is no way you can simulate the click behavior. What it does is to call the function that handle given event. These two are total different. For example:
$('#test').click(function() {
console.log("Clicked");
});
$('#test').dblclick(function() {
console.log("Double Click");
});
$('#test').trigger('click');
$('#test').trigger('click');
Despite of rapidly trigger two clicks, the double click will not trigger.

Related

Simple but strange HTML, jQuery issue. Function loops with no reason

I wrote the code in javascript (jQuery), that allows a user with every click of a button to create a "box" on the web site and to get an alert message after this box was clicked.
It works like this:
1) When the user presses the button "Add (#addBox)" - jQuery appends a new line to the HTML file, that creates the "box" (it looks like a box because of the CSS code).
2) If the user presses the box, it sends out the alert message "Hello".
But if I add multiple boxes and then click on the first one, instead of sending out one alert message, it sends it out as many time as the number of boxes been created.
Example:
1) I have 1 box. By pressing on it, I receive 1 alert message.
2) I have 2 boxes. By pressing on the top one, I receive 2 alert messages.
By pressing on the second one, I receive 1 message.
3) I have 3 boxes. By pressing on the top one, I receive 3 alert messages.
By pressing on the second one, I receive 2 messages.
By pressing on the third one, I receive 1 message.
The function of sending an alert message is looping for some reason.
And so here is the code:
function addBox()
{
$("#addBox").on("click", function () {
$("#addBox").append('<div class="desiredBox">Say Hello</div>');
}
boxCount();
});
}
function boxCount()
{
$(".desiredBox").on("click", function () {
alert("Hello");
});
}
Any ideas, how to make them send only one message each, preventing the function "boxCount()" from looping?
Every time the function boxCount is invoked an event handler is added to existing elements i.e. ".desiredBox". thus you are getting multiple alerts.
As you are creating elements dynamically.
You need to use Event Delegation. You have to use .on() using delegated-events approach.
General Syntax
$(document).on(event, selector, eventHandler);
Ideally you should replace document with closest static container.
Complete code
$("#addBox").on("click", function () {
$("#addBox").append('<div class="desiredBox">Say Hello</div>');
});
$(document).on('click', '.desiredBox', function(){
//Your code
});
Use event delegation so you don't keep adding the click event to .desiredBox over and over again:
$(document).on("click", "#addBox", function () {
$("#addBox").append('<div class="desiredBox">Say Hello</div>');
$(".desiredBox").trigger("click");
});
$(document).on("click", ".desiredBox", function () {
alert("Hello");
});

Javascript 'Multiple Click Simulation' issue

I'm trying to simulate multiple button-type clicks with Javascript, the webpage I'm running it on has around 10 of 1 type of button and 1 of the other.
I'm wanting the JS to click ALL of the buttons on the webpage that match the markup of the first button, then after that's completed, finally click the other.
I've managed to get it to easily click all 10 of the first button, but I'm starting to struggle with the other button.
The markup for the first button is this; http://pastebin.com/aRNpjG0n
So running this Javascript, I am able to click these buttons with a 2 second delay;
window.setInterval( function(){
var inputs = document.getElementsByClassName('x-button-litebutton-wrapper');
for(
var i=0; i<inputs.length;i++
)
{inputs[i].click();}
},
2000);
The markup for the other button is available here; http://pastebin.com/baw32HjK
I'm assuming the ID for the second button is 'x-btn-text', if that's the case, then my issue would simply be how to implament it within my existing Javascipt (Above)
Any help at all would be greatly appreciated, since I've not managed to find anything on here about simulating more than 1 button click at a time.
I am not sure what your problem actually is, but here is a version in jQuery (to keep it simpler):
http://jsfiddle.net/t9r4ru0m/
$(function () {
// Debug - write out log that the items were clicked
$('.x-button-litebutton-wrapper').click(function () {
console.log($(this).attr('class'));
});
$('.x-btn-text').click(function () {
console.log($(this).attr('class'));
});
setTimeout(function () {
console.log('clicking');
$('.x-button-litebutton-wrapper').click();
// Now click the rest of the buttons
setTimeout(function() {
$('.x-btn-text').click();
}, 3000);
}, 3000);
});

JavaScript Restrict User From Clicking Button Multiple Times

I am trying to restrict the user from clicking on a button multiple times. They can click on the button once when the page loads. If the page is reloaded the same should apply the user can click on the button only once.
I am using the following code however it doesn't seem to work for me
$("#doAccess").click(function() {
$("#doAccess").removeAttr('onclick');
DoSave();
});
Disable the button after it's been clicked
var accessBtn = $('#doAccess');
accessBtn.click(function() {
accessBtn[0].disabled = true;
DoSave();
});
Sounds like what you really need is:
$("#doAccess").one('click', DoSave);
jsFiddle example
.one() - Attach a handler to an event for the elements. The handler is executed at most once per element per event type.
Why not this?
$("#doAccess").once('click', function() {
DoSave();
});
You should probably also gray out or disable #doAccess, whatever it is.

When I dblclick, it runs .click twice

I have 2 functions when you click on an item, .click and .dblclick
The problem is, that when you dblclick, it runs the .click function twice.
Is there a way to fix this?
$(".item").click(function() {
if (price[this.id] === 1) {
consoleUpdate("This item is worth " +price[this.id]+ " coin");
}
}
$("#fishItem").unbind("dblclick").bind("dblclick").dblclick(function() {
coins = coins+1;
coinUpdate();
invFish1--;
if (invFish1 === 0) {
$("#fishItem").appendTo("#itemStage");
}
});
Per the jQuery documentation for the dblclick event:
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.
You want to change your events so that you don't have a .click and .dblclick on the same element.
http://api.jquery.com/dblclick/
var cnt=1;
$( "#target" ).click(function(e) {
if(cnt==1)
{
// action on single click if you dont want anything in in single click then use here
e.preventDefault();
}else{
// work on double click
cnt=1;// again set counter
}
cnt++;
});
reference e.preventDefault();
As others mentioned, you can't really bind both click and double click to the same item. There are, however, workarounds.
One way to handle this would be to handle the click code and then check for double-click:
var lastClickTime = 0;
$(".item").click(function() {
var thisClickTime = (new Date).getTime();
if (thisClickTime - lastClickTime < 500) {
//Double-click
}
else {
//Click
}
lastClickTime = thisClickTime;
});
This code essentially captures a "last click time" and if this click time is less than 500 milliseconds from the last click time, then it fires the double-click code. Otherwise it will fire the click code.
The downside with this is that the click-code will be called first and then the double-click code. Also, you're forcing your users into a 500ms double-click. While this is pretty standard, it's not guaranteed. (Slower clickers may have trouble with this.)
A JSFiddle that demonstrates this technique.
You could improve this code by setting a 500ms timeout for the click code and then cancelling the click event if a double-click is fired. The downside with this is that it will force a 500 ms delay between the click and the "click" code.
A JSFiddle that demonstrates the timeout.
If you don't mind handling one single-click, look at the event object details attribute. It is the number of clicks.
$(".item").click(function(event) {
if (event.details === 1) {
//handle single click
} else if (event.details === 2) {
// handle double click
}
}

jQuery .click function executes twice in a row

I'm working on my first program using jQuery, but I'm having an issue. I have a dialog pop up on pageLoad that asks the user to select a date and a turn. Right now, for debugging purposes, I have it alert every time .click() executes, and for some reason, it seems like it executes before the user clicks and immediately afterward.
There are three radio buttons, Turns 1, 2, and 3. When the user clicks Turn 1, the alert should say "1". When the user clicks Turn 2, the alert should say "2", etc. But for some reason, it alerts the previous value as well as the new one. I searched all of my code, and there is only one alert, so I can't figure out what is calling click() twice. I've tested it in IE and Chrome and it happened both times.
This is my .click() function:
$("#turn-radio")
.click(function () {
turnvalue = $("input[name='turn-radio']:checked").val();
alert(turnvalue);
});
If you check this jsfiddle, you'll see the rest of my code, which will hopefully make it easier to figure out what my problem is.
Thanks!
You need to change selector: as your radio button IDs are different and you were giving name as a selector that's why you were facing that problem:
$("input[name='turn-radio']")
.click(function () {
turnvalue = $("input[name='turn-radio']:checked").val();
alert(turnvalue);
});
Updated Fiddle
changing
$("#turn-radio") to $("#turn-radio label")
causes only one popup displaying the previous value
But, personally i would
$("#turn-radio input").change( function() { /* do stuff */ } )

Categories

Resources