Wait for user confirmation before triggering event - javascript

I'm trying to figure out how events works and how to wait for a second event to trigger before the original event is being executed.
$.fn.customConfirm = function (message){
// Create modal
// then ...
$(confirmModal).find("modal-footer a").click(function(e2){
e2.preventDefault();
return ($(this).hasClass("dialogConfirm")); // Returns true if option has class dialogConfirm
});
};
$("a[data-confirm]", click(function(e){
if (!$.customConfirm($(this).attr("data-confirm")))
return false; // Only if customConfirm returns false
// Continue
});
This works like a charm. customConfirm creates a bootstrap modal with 2 buttons (confirm/cancel) and sets the data-confirm attribute value as the modal-body html.
What I don't know how to solve is how to handle the event e based on the user interaction with the modal. As of now it just shows the modal dialog and the original event seems to do nothing.

I solved it by adding the attribute data-confirmed to the clicked element if the user confirms and then triggering a second click() on the original element.
$.fn.customConfirm = function (message){
var handle = $(this);
// Create modal
// then ...
$(confirmModal).find("modal-footer a").click(function(e2){
e2.preventDefault();
$(handle).attr("data-confirmed", ($(this).hasClass("dialogConfirm")))[0].click();
return false;
});
};
$("a[data-confirm]").click(function(e){
if ($(this).attr("data-confirmed") !== "true")
{
e.preventDefault();
$(this).customConfirm();
return false;
}
$(this).removeAttr("data-confirmed");
// Continue
});

Related

Choose only the first button

I'm trying to do that only one can happen, if you click yes or no. As it is now if you click "no" in the first time and "yes" in the second time, it will execute it twice .
function confirm() {
$("#no").one("click", function(){
return false;
});
}
$("#yes").one("click", function () {
//do something
});
thanks for help
Both events are attached at document.ready I assume, which means they will remain active indefinitely unless you specify otherwise.
The following approach is fairly basic, just set a variable 'hasClicked' to false. And as soon as either one of them is clicked, set 'hasClicked' to true. Each button has an if-structure that only executes the code IF 'hasClicked' is false.
Try the following:
var hasClicked = false;
function confirm(){
$("#no").one("click", function(){
if (!hasClicked){
hasClicked = true;
return false;
}
});
$("#yes").one("click", function () {
if (!hasClicked) {
hasClicked = true;
//do something
}
});
}
As you can't unbind an event binded with one() check this answer
So you'll have to work around like this:
function confirm() {
$("#no").bind("click", function(){
$(this).unbind(); // prevent other click events
$("#yes").unbind("click"); // prevent yes click event
// Do your stuff
});
}
$("#yes").bind("click", function () {
$(this).unbind();
$("#no").unbind("click");
// Do your stuff
});
Assign your buttons a class called confirmation. Set a event handler based on class. Read the value of the button to decide what you want to do.
$(".confirmation").one("click", function(){
if($(this).val() === 'yes'){
//do something
}else{
return false;
}
}

Selectize.js: onItemAdd event triggered when silently adding an item

Using Selectize.js, I'm trying to initialize the dynamically pre-select one of the item of the list without triggering the onItemAdd event. In the following code, the event is triggered even if the silent parameter is truthy:
$(function () {
$('select').selectize({
onItemAdd: function () {
alert("Add item");
}
});
// this triggers an the event
$('select')[0].selectize.addItem('2', true);
});
JSFiddle: http://jsfiddle.net/zuzat0dc/1/
According to the documentation:
addItem(value, silent): "Selects" an item. Adds it to the list at the current caret position. If "silent" is truthy, no change event will be fired on the original input.
Any idea how to avoid triggering the onItemAdd event? Is the silent parameter b0rked or should I use the change event instead?
A quick fix that worked for me was to keep a state flag and refer to it in the event handler...
$(function () {
var initialising = true;
$('select').selectize({
onItemAdd: function () {
if(!initialising) {
alert("Add item");
}
}
});
// this triggers an the event
$('select')[0].selectize.addItem('2', true);
initialising = false;
});
The silent parameter in addItem(value, silent) affects only to the fact whether or not the change event. You can't avoid item_add event with silent = true.
The only thing that worked for me was to store item_add event locally, remove it from selectize instance and set it back after I added the item:
onItemAdd: function(val) {
var e = this._events['item_add'];
delete this._events['item_add'];
this.addItem(123);
this._events['item_add'] = e;
}

2 anchor with one click

So here is my code
prev
prev
How do I make it both click if I click any of it ?
If I click .slider-1-prev, at the same I click .slider-2-prev
If I click .slider-2-prev, at the same I click .slider-2-prev
How to make it by javascript ?
As well as triggering the event on the other link, you need to shield against infinite repeating (e.g. with a shield variable):
var inClick = false;
$(document).ready(function {
$('.slider-1-prev').on('click', function {
if (!inClick) {
inClick = true;
$('.slider-2-prev').trigger('click');
inClick = false;
}
});
$('.slider-2-prev').on('click', function {
if (!inClick) {
inClick = true;
$('.slider-1-prev').trigger('click');
inClick = false;
}
});
})
If you want a shorter version, you can listen for both on one handler and click "the other":
var inClick = false;
$(document).ready(function {
var $sliders = $('.slider-1-prev,.slider-2-prev');
$sliders.on('click', function {
if (!inClick) {
inClick = true;
// Click the one that was not clicked (not this)
$sliders.not(this).trigger('click');
inClick = false;
}
});
})
Another option is a bit more complicated as you need to turn the handler off and then on again. Stick with this simple one for now.
The on/off approach involves disabling the handling while executing it, so that it will not trigger again until you reconnect it. The downside is you need to reference a separate function so that it can effectively reference itself:
$(document).ready(function {
var $sliders = $('.slider-1-prev,.slider-2-prev');
// Define separate named function
var clickTheOtherOne = function(){
// Disable the click
$sliders.off('click');
// Click the one that was not clicked (not this)
$sliders.not(this).trigger('click');
// Reenable the click handler
$sliders.on('click', clickTheOtherOne);
}
// Initial enabling of the handler
$sliders.on('click', clickTheOtherOne);
});
If they're going to behave the same, why not define only one function for both?
$('.slider-1-prev, .slider-2-prev').click(function(){
//... mutual code
});
I can't figure why you need to do what you ask, but try this approach:
js code:
// this will work on all classes that start with 'slider-prev'
$('*[class^="slider-prev"]').on('click',function{
// do something
});
Of course you will need to alter your htm code to:
prev
prev
this should do the trick
$(document).ready(function{
$('.slider-1-prev').on('click',function{
$('.slider-2-prev').trigger('click');
});
$('.slider-2-prev').on('click',function{
$('.slider-1-prev').trigger('click');
});
})
Try this -
$('.slider-1-prev').click(function(){
$('.slider-2-prev').trigger('click');
});
// If you need the opposite, then do -
$('.slider-2-prev').click(function(){
$('.slider-1-prev').trigger('click');
});

How to disable the click if a function is in active status

I have created a fiddle of my function here( http://jsfiddle.net/rhy5K/10/ ) . Now i want to disable the button click i.e play/pause if the sound is playing like Get ready,5,4,3,2,1 .
I know only how to disable the form submit button , but I am very confused how to disable the click in my case the hyperlinks.
Explanation using code example:
I want to disable this
PLAY
click, while interpreter is executing the below code:
var playGetReady = function (done) {
var ids = ['audiosource', 'a_5', 'a_4', 'a_3', 'a_2', 'a_1'],
playNext = function () {
var id = ids.shift();
document.getElementById(id).play();
if (ids.length) {
setTimeout(playNext, 1000);
} else {
done();
}
};
playNext();
};
Warning: This JS fiddle demo may play sound on load
You may try this (Changes in following function), but not sure if this is you want and maybe there are other ways to do it.
App.prototype.start = function () {
var self = this;
// unbind for a while
self.$button.unbind('click', self.buttonHandler); // <--
var start = function () {
// start countdown
self.intervalHandle = setInterval($.proxy(self.tick, self), 1000);
// bind again
self.$button.click($.proxy(self.buttonHandler, self)); // <--
// change button text to PAUSE
self.$button.text('PAUSE');
};
if (this.newTimer) {
playGetReady(start);
} else {
start();
}
};
DEMO.
In jquery, it can be done easily by cancel default action. Here's the sample.
$("#btn_start").click(function(event){
if(not_active_flag){
// Prevent anchor to active
return false;
}else{
// Anchor active as usual
return true;
}
});
In your case, the link will ultimately call this.buttonHandler, which has the following code:
App.prototype.buttonHandler = function (e) {
e.preventDefault(); // prevent anchor default action
this.toggle(); // toggle play/pause
};
Because buttonHandler is attached before playGetReady is executed, it is not possible to let playGetReady attach a click handler to that anchor element that uses .stopImmediatePropagation() to prevent the other click handler from executing.
In this case #gp.'s solution in the comments is most likely the best solution. In your case you might even be able to use a local variable in your app. If you use a global variable, reference it with window.yourglobalvariable. If you use a local variable, make sure you define it somewhere and reference it with this.yourvariable. Change your buttonHandler to:
App.prototype.buttonHandler = function (e) {
e.preventDefault(); // prevent anchor default action
if( this.soundready )
this.toggle(); // toggle play/pause
};
On the appropiate place make this variable false to prevent the 'button' from working. When the button should work, change the variable to true. I think that should be just before done() in the code you have in your question, but you probably have a better idea in what order the code is executed.

Disable live event on current method

In the view I have the following class
.class{"data-id" => time.id}
At the end of the view I enable the live click event
$('.class').live("click", function() {
window.orc.time.stopCount();
window.orc.time.whenClicked(#{class.id}, #{class.time}, #
{class.start});});
In coffeescript i have the following function
time.whenClicked = (class.id, time_dur, time_start) ->
ct = time_entries.to_time(time_dur, time_start)
$("div[data-id=#{time_id}]").addClass "ajax"
$("div[data-id=#{time_id}]").html("<input id=\"editbox\" size=\"8\" type=\"text\" value=\"#{ct}\">")
$("#editbox").bind "keyup", (event) ->
...
In the whenClicked function I need the live("click") to be disabled. If I try
$(".class").die("click")
it works, but then the click event will be re-enabled only after I refresh the page, and that's not what I need.
Is there a solution to disable the click event untill the function is executed?
Don't disable the handler. Just implement a boolean flag so you know if the method is already running or not. You can then immediately return from the handler in that case:
var isBusy = false;
$('.class').live('click', function(){
if(isBusy) return;
isBusy = true;
window.orc.time.stopCount();
window.orc.time.whenClicked(/* some params */);
isBusy = false;
});

Categories

Resources