jQuery custom Confirm - javascript

I want to have a very simple custom dialog. When I click remove, I want a simple panel opens up with the option to confirm or cancel. If confirmed, more things will run.
Since I want to use this confirmation in different files, this was my approach:
In index.js that runs on all pages I have:
var confirmation = -1
$(document).ready(function(){
$('html').on({
click: function() {
confirmation = 1;
}
},'#confirmation_yes');
$('html').on({
click: function() {
confirmation = 0;
}
},'#confirmation_no');
});
function confirmAction(callback)
{
if( confirmation == 1 ) {
$('#popup_panel').slideUp('slow', function(){
$('#popup_fader').fadeOut('fast');
});
confirmation = -1;
callback(true);
}
if( confirmation == 0 ) {
$('#popup_panel').slideUp('slow', function(){
$('#popup_fader').fadeOut('fast');
});
confirmation = -1;
callback(true);
}
setTimeout(confirmAction, 50)
}
So my idea was that then inside other JS files, we have
$('#element').click(function(){
confirmAction(function(result){
// do my stuff
});
})
So when I do this, the system returns error and says "callback" is a not a function. What is wrong with this code?
Thanks

I made another approach. It is based on jQueryMobile but can also be used with normal jQuery after a few minor modifications. The basic is simple: you call a function that opens the popup and adds two buttons that react on functions that you provide by calling the opener-function. Here is my example:
function jqConfirm(data) {
var container = $('#genericConfirm');
container.find('h1').html(data.title); // title of the confirm dialog
container.find('p').html(data.message); // message to show
// .off('click') removes all click-events. click() attaches new events
container.find('.yes').off("click").click(data.yes); // data.yes/no are functions that you provide
container.find('.no').off("click").click(data.no);
container.popup({ positionTo: "window" }).popup("open"); // .popup("open") opens the popup
}
var confirmData = {
title: "Send this message?",
message: "Are you sure you want to send this message?",
yes: function() {
sendMessage();
$('#genericConfirm').popup("close");
},
no: function() {
$('#genericConfirm').popup("close");
}
};
jqConfirm(confirmData); // you open the popup with this function (indirectly)
And the HTML part (jQueryMobile specific, must be modified a bit to match plain jQuery)
<div data-role="popup" id="genericConfirm" data-overlay-theme="a" data-theme="c" style="max-width:400px;" class="ui-corner-all">
<div data-role="header" data-theme="a" class="ui-corner-top">
<h1>Title</h1>
</div>
<div data-role="content" data-theme="d" class="ui-corner-bottom ui-content">
<p style="margin-bottom: 15px;">Message</p>
<div class="ui-grid-a">
<div class="ui-block-a">
Cancel
</div>
<div class="ui-block-b">
Ok
</div>
</div>
</div>
</div>

Attach another handler to the button that deals with the logic. After you are done with the dialog, simply remove the dialog to get rid of the handlers. If you create an other dialog later, maybe with the same or an other layout, you can define different handlers for that dialog. As events 'bubble' up, both the handler on the button itself, as the handler on html (that only fires when the button is clicked), will be fired.
The following is merely pseudo-code, but it should give you an idea what you can do with this:
//This will create the html for your dialog
createMyFancyDialog();
showDialog();
//This is where you'll do the logic for this dialog
$('#confirmation_yes').on( 'click', function() {
doWhatEveryIWantToDo();
//After this dialog is done, destroy the dialog.
//This will get rid of the handlers we don't need in a future dialog.
//The handler attached to html will persist.
destroyDialog();
} );
$('#confirmation_no').on( 'click', function() {
doSomethingMean();
//After this dialog is done, destroy the dialog.
//This will get rid of the handlers we don't need in a future dialog.
//The handler attached to html will persist.
destroyDialog();
} );

I've tried to rewrite and fix your code, but there are too many things to adjust.
So, I strongly recommend you to rewrite your code in a simpler way, like this:
<button id="element">Element</button>
<div id="popup_panel" style="display: none;">
<p>Your msg?</p>
<button id="confirmation_yes" >Yes</button>
<button id="confirmation_no">No</button>
</div>
<script>
$(document).ready(function () {
$('#confirmation_yes').click(actionConfirmed);
$('#confirmation_no').click(actionNotConfirmed);
$('#element').click(showPopupPanel);
});
function actionConfirmed() {
$('#popup_panel').slideUp();
// User confirmed. Now continue.
// e.g. alert('Yes was clicked');
}
function actionNotConfirmed() {
$('#popup_panel').slideUp();
// User said no.
}
function showPopupPanel() {
$('#popup_panel').slideDown();
}
</script>
You can see this code in action here:
http://jsfiddle.net/LGTSK/

Keep it simple:
<!doctype html>
<html lang="en">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<input id='yes' type="button" value="Yes" data-result="Yes" />
<input id='no' type="button" value="No" data-result="No" />
<script type="text/javascript">
var result;
function confirmAction() {
if (result) alert(result);
else setTimeout(confirmAction, 100);
}
$(function() {
$('#yes, #no').on('click', function(e) {
result = $(this).attr('data-result');
});
confirmAction()
});
</script>
</body>
</html>

Related

Why my plugin fires multipe callback or clicks

I am creating my simple jQuery plugin that can be use to attach for any action's confirmation. But facing very strange issue, It work fine for single element click, But when i am going to click for second element which also bind with my plugin it work fine but it's also fires for previous clicked element as well.
(function ($) {
$.fn.BootConfirm = function (options) {
// Establish our default settings
var settings = $.extend({
message: 'Are you sure about this ?',
complete: null
}, options);
var self = this;
var cointainer = '\
<div class="modal fade" id="confirmBoot" role="dialog" aria-labelledby="confirmDeleteLabel" aria-hidden="true">\
<div class="modal-dialog">\
<div class="modal-content">\
<div class="modal-header">\
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>\
<h4 class="modal-title">Confirm action</h4>\
</div>\
<div class="modal-body">\
<p>Are you sure about this ?</p>\
</div>\
<div class="modal-footer">\
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>\
<button type="button" class="btn btn-success btn-ok" id="confirm">Ok</button>\
</div>\
</div>\
</div>\
</div>';
return this.each(function () {
var self = this;
$(this).click(function () {
if (!$('#confirmBoot').length) {
$('body').append(cointainer);
}
if (settings.message) {
$('#confirmBoot').find('.modal-body').text($(this).attr('data-confirm'));
}
$('#confirmBoot').modal({ show: true });
if ($.isFunction(settings.complete)) {
$('#confirmBoot').find('.btn-ok').click(function () {
$.when(settings.complete.call(this, self)).done(function () {
$('#confirmBoot').modal("hide"); // Alerts "123"
});
});
}
});
});
}
}(jQuery));
This is my callback function :
function kaushik(myObject) {
ManageAcriveProducts(myObject);
};
and i am calling it by following way
$('a[data-confirm]').BootConfirm({
complete: kaushik
});
For more detail check this js fidder Jsfiddle. Can anyone one share possible solution or better way to do this. Or is there any better way to achieve this ?
The problem is that you're assigning a click on your btn-ok on every click event on a bootconfirmed object. And each click is linked to the object that has been clicked, so it ends up in your callback every time you click btn-ok.
One simple fix, though I'm not sure it's the best, is to remove the click on your btn-ok after the action is complete. Like this:
$.when(settings.complete.call(this, self)).done(function () {
$('#confirmBoot').modal("hide");
$('#confirmBoot').find('.btn-ok').off('click');
});
Working fiddle: http://jsfiddle.net/ywunutyw/
EDIT:
A little improvement on previous solution, it might need some adjustments, since I didn't look into details, but it should give you some ideas. To prevent adding click events and removing them every time user clicks on a button, you can define the click on modal window outside click behavior of each active/inactive button. And on click of active/inactive you define target that will be used in modal confirmation. Like this:
Just before calling behaviors with this.each:
$(document).on('click', '#confirmBoot .btn-ok',
function (e) {
if ($.isFunction(settings.complete)) {
console.log(self)
$.when(settings.complete.call(this, click_origin)).done(function () {
$('#confirmBoot').modal("hide");
});
}
});
Then on the click event of you active/inactive:
click_origin = e.target;
See fiddle: http://jsfiddle.net/ywunutyw/1/

javascript event handlers list

I am trying to prioritize click event in case two events click and change are fired.
I have a global function similar to "ValidateOnChange" and "ValidateOnClick" to validate input of text box on change and on click event.
Enter some text, it shows up error message. Then try to input correct value and click the Submit button, the error vanishes and this makes user to click the button twice. Here I am trying to fix this double click.
Here is mock up code:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<div>Enter any string:</div>
<div><input type="text" id="txtInput" ></input></div>
<div id="divError" style="color: red; display: none;">Please enter 0</div>
<input type="button" value="Submit" id="btnSubmit" ></input>
<script type="text/javascript">
var mouseevent_var = null;
function ValidateOnChange(e) {
var input = $('#txtInput').val();
if (input == '0') {
$('#divError').hide();
} else {
$('#divError').show();
}
}
function ValidateOnClick(e){
alert("Hurray!!! You got it right!");
}
$('#txtInput').mousedown(function (e) {
mouseevent_var = e;
});
jQuery(document).ready(function(){
$('#btnSubmit').click(function(e){
ValidateOnClick(e);
});
$('#txtInput').change(function(e){
ValidateOnChange(e);
});
//User don't want error when they are typing in.
//$('#txtInput').keyup(function() {
//$('#txtInput').trigger("change");
//});
});
</script>
</body>
</html>
The keyup event seemed to be solution but users don't want the error to popup when they are typing in.
Is there any way to list all the triggered events so that I could filter "mousedown" and "mouseup" events for submit button? Or is there any alternative way to prioritize click event ?
There can be many alternatives depending on the situations. I have made few minor changes to avoid the double click issue (comments amended). Basically we need to bind the mousedown event on the button object. There we will set a temporary flag variable to true. In the same time if input's change event gets fired then you can skip the checking if the temporary flag variable is true. Reason behind the double click for triggering the button's click event is better explained here: How to get jQuery click event after append in change event handler
Your updated js code below:
var mouseevent_var = false;
function ValidateOnChange(e) {
// Skip validation if the change event is fired due to user's click on submit button
if(mouseevent_var){ return false; }
var input = $('#txtInput').val();
if (input == 0) {
$('#divError').hide();
} else {
$('#divError').show();
}
}
function ValidateOnClick(e){
mouseevent_var = false; // Reset mouseevent_var to false
alert("Hurray!!! You got it right!");
}
$('#btnSubmit').mousedown(function (e) {
mouseevent_var = true;
});
jQuery(document).ready(function(){
$('#btnSubmit').click(function(e){
ValidateOnClick(e);
});
$('#txtInput').change(function(e){
ValidateOnChange(e);
});
//User don't want error when they are typing in.
//$('#txtInput').keyup(function() {
//$('#txtInput').trigger("change");
//});
});
The above code is just a fix as per your need. But there are other better alternatives too. Ideally you should not have two different validation functions for validating same fields on different events. You must think of managing it with a single function.

Jquery popup windows automaticly pops up

I've gotten an piece of Jquery code which lets the user click a link which will open an popup with information. But I don't know how to modify it so that the popup automaticly opens up when the user loads the page.
Jquery:
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
jQuery(document).ready(function ($) {
$('[data-popup-target]').click(function () {
$('html').addClass('overlay');
var activePopup = $(this).attr('data-popup-target');
$(activePopup).addClass('visible');
});
$(document).keyup(function (e) {
if (e.keyCode == 27 && $('html').hasClass('overlay')) {
clearPopup();
}
});
$('.popup-exit').click(function () {
clearPopup();
});
$('.popup-overlay').click(function () {
clearPopup();
});
function clearPopup() {
$('.popup.visible').addClass('transitioning').removeClass('visible');
$('html').removeClass('overlay');
setTimeout(function () {
$('.popup').removeClass('transitioning');
}, 200);
}
});
});//]]>
</script>
Link to activate the code:
Link
Content of popup window:
<div id="example-popup" class="popup">
<div class="popup-body"> <span class="popup-exit"></span>
<div class="popup-content">
<h2 class="popup-title">Terms and Conditions</h2>
<p>
<h5><font color="grey">Please take time to read the following...</font></h5>
</div>
</div>
</div>
<div class="popup-overlay"></div>
I've tried modifying it mysql, but it didn't work out. As I'm not an expert in Jquery.
I know it is a big ask, but the code is here. And I know some geek can easily find what I need :)
So real quick. Instead of having the user to click the link to open the popup. I want the popup to automaticly open
Reasonably simple when you trigger a click on the element you want after you register the click handler.
/* your original code stays mostly the same except for chaining methods after it*/
$('[data-popup-target]').click(function () {
$('html').addClass('overlay');
var activePopup = $(this).attr('data-popup-target');
$(activePopup).addClass('visible');
/* now click the first one */
}).first().click();
ID's must be unique in a page, so you should change the duplicates on the popup link and popup container if they are the same as shown

Javascript/jQuery close notification fade out

Hello I have made a basic sticky notification that shows on my website, I am trying to make it so you can manually close it by clicking a button but it won't seem to work? Here is my code:
<script>
$(function() {
$("#closeBtn").click(function () {
$(".notification").fadeOut(500);
return false;
});
});
</script>
<div class="notification" id="success">
Message sent
<a href="#" id="closeBtn">
<div class="close">
<div class="closeTxt">X</div>
</div>
</a>
</div>
try using .on() for the elements created dynamically
$(document).on('click','#closeBtn',function() {
$(".notification").fadeOut(500);
return false;
});
Because the element is added to the DOM after page load, you need to use .on() instead of .click():
$(document).on('click', '#closeBtn', function (e) {
e.preventDefault();
$('.notification').fadeOut(500);
});
When the element is added Dynamically you have two choices.
function myFadeOut() {
$(".notification").fadeOut(500);
return false;
}
Using the on:
$(document).on('click', '#closeBtn', myFadeOut);
Or more clean, adding the click directly on the node when you generate it:
var $myNode = $('<div class="someNode"></div>');
$myNode.click( myFadeOut);
$(".foobar").append($myNode);

properly disabling the submit button

this is the code that I use to disable the button
$("#btnSubmit").attr('disabled', 'disabled')
$("#btnSubmit").disabled = true;
and this is my submit button
<input id="btnSubmit" class="grayButtonBlueText" type="submit" value="Submit" />
the button although looks disabled, you can still click on it.. This is tested with FF 3.0 and IE6
Am I doing something wrong here?
If it's a real form, ie not javascript event handled, this should work.
If you're handling the button with an onClick event, you'll find it probably still triggers. If you are doing that, you'll do better just to set a variable in your JS like buttonDisabled and check that var when you handle the onClick event.
Otherwise try
$(yourButton).attr("disabled", "true");
And if after all of that, you're still getting nowhere, you can manually "break" the button using jquery (this is getting serious now):
$(submitButton).click(function(ev) {
ev.stopPropagation();
ev.preventDefault();
});
That should stop the button acting like a button.
Depending on how the form submission is handled you might also need to remove any click handlers and/or add one that aborts the submission.
$('#btnSubmit').unbind('click').click( function() { return false; } );
You'd have to add the click handler's again when (if) you re-enable the button.
You need to process Back/Prev button into browser.
Example bellow
1) Create form.js:
(function($) {
$.enhanceFormsBehaviour = function() {
$('form').enhanceBehaviour();
}
$.fn.enhanceBehaviour = function() {
return this.each(function() {
var submits = $(this).find(':submit');
submits.click(function() {
var hidden = document.createElement('input');
hidden.type = 'hidden';
hidden.name = this.name;
hidden.value = this.value;
this.parentNode.insertBefore(hidden, this)
});
$(this).submit(function() {
submits.attr("disabled", "disabled");
});
$(window).unload(function() {
submits.removeAttr("disabled");
})
});
}
})(jQuery);
2) Add to your HTML:
<script type="text/javascript">
$(document).ready(function(){
$('#contact_frm ).enhanceBehaviour();
});
</script>
<form id="contact_frm" method="post" action="/contact">
<input type="submit" value="Send" name="doSend" />
</form>
Done :)

Categories

Resources