Replacement of alert/prompt/confirm dialog boxes - javascript

I want to replace the default alert/prompt/confirm with my own and do not want to use a plugin. I did the styling but enable to figure out the action when the buttons are clicked (Ok/cancel/etc..). Here my code so far.
function jPromt(title,content,type,callback){
var alert = $('.resources').find('.alert').clone(); //basic barebone
alert.find('h3').html(title);
alert.find('.content').prepend(content);
var options = {
"_prompt" : {"OK" :""},
"_confirm": {"No" :"recomended", "Yes":""},
"_input" : {"Cancel":"recomended", "OK" :""}
}
for (var prop in obj) { // Create buttons
if (obj.hasOwnProperty(prop)) {
var btn = "<button class='button_"+prop+" "+obj[prop]+"'>"+prop+"</button>";
alert.find('.buttons').append(btn);
}
}
$('.resource_loader').append(alert)
$('body').append(alert).center().fadeIn('fast');
// This is here I'm not realy sure what to do whit callbaks for each button.
//if (callback && typeof(callback) === "function") {
// callback();
//}
}
I want it so that you can call jPromt() and the callback for each buttons will execute like so: or similar to it:
....
'ok', function(){
//do stuff if ok was clicked
},
'cancel', function(){
// canel was clicked, do stuff
}
JSFiddle: http://jsfiddle.net/CezarisLT/u6AYe/5/
Thank you in advance. I will surely select your answer as correct.

You can make that work with only a few modifications:
Pass an object as the callback parameter (I'd rename it to callbacks), where the keys represent the buttons, using the same format you defined for the options ("Yes", "No" etc). your call should look like this:
jPromt("test THE title","testing the contents","_confirm", {
'No' : function(){
alert("testing NO");
},
'Yes' : function(){
alert("testing YES");
}
});
Make btn a jQuery object inside your loop over obj, so you can attach a handler
Check if the callbacks parameter has a handler for the current prop; if yes, attach to btn.
Demo: http://jsfiddle.net/u6AYe/7/

What you can do is...
give your buttons actual click handlers invoking the callback
in your callback you inspect which button was actually clicked
Something like...
function jPromt(title,content,type,callback){
var myAlert = $('.resources').find('.alert').clone(); //basic barebone
myAlert.find('h3').html(title);
myAlert.find('.content').prepend(content);
var options = {
"_prompt" : {"OK" :""},
"_confirm": {"No" :"recomended", "Yes":""},
"_input" : {"Cancel":"recomended", "OK" :""}
};
if( options.hasOwnProperty(type) ){
obj = options[type];
}
for (var prop in obj) { // Create buttons
var $btn = $("<button class='button_"+prop+" "+obj[prop]+"'>"+prop+"</button>");
$btn.attr('btn-type',prop.toUpperCase());
myAlert.find('.buttons').append($btn);
$btn.click(callback);
}
$('body').append(myAlert.show());
}
jPromt("test THE title","testing the contents","_confirm",
function(){
answer = $(this).attr('btn-type');
if(answer == 'YES'){
alert("Yes!");
}else{
alert("No!");
}
}
);
See http://jsfiddle.net/u6AYe/8/ ...

Related

How can I find the element clicked on inside a jQuery handler?

I'm trying to do a specific action on the clicked element if an argument is passed in the on click method in jQuery. When I try to access this it's referencing the entire window instead of the clicked on element. How would I access the clicked on element in the handler?
Here's the code I'm using:
var myfunction = function(action) {
var content;
var $this = $(this);
if(action === "one") {
$(".output").text("clicked on one");
$this.addClass("one");
}
if(action === "two") {
$(".output").text("clicked on two");
$this.addClass("two");
}
};
$("#button").on("click", function(event) {
myfunction("one");
});
$("#button2").on("click", function(event) {
myfunction("two");
});
I set up an example on jsbin here. Any help would be appreciated.
There are several ways to do this.
JQUERY WAY:
Within your jquery click event handlers you have the event object. It has a property called target which is what you're looking for.
Change this: $this.addClass("one");
To this: $(event.target).addClass("one");
You can also do this: event.target.className = "one"
And do for "two" as well obviously...
VANILLA WAY:
You can just pass in an extra argument representing your clicked element.
var myfunction = function(action, element) {
var content;
if(action === "one") {
$(".output").text("clicked on one");
$(element).addClass("one");
// or event.target.className = "one"
}
if(action === "two") {
$(".output").text("clicked on two");
$(element).addClass("two");
// or event.target.className = "two"
}
};
$("#button").on("click", function(event) {
myfunction("one", this);
});
$("#button2").on("click", function(event) {
myfunction("two", this);
});
You can use Function.prototype.call:
$("#button2").on("click", function(event) {
myfunction.call(this, "two");
});
or store the action as an attribute on your element, bind your handler directly and query the attribute.
var myfunction = function() {
var content;
var $this = $(this);
var action = $this.attr('data-action');
if (action === "one") {
$(".output").text("clicked on one");
$this.addClass("one");
} else if (action === "two") {
$(".output").text("clicked on two");
$this.addClass("two");
}
};
$("#button2").on("click", myfunction);
this refers to the object the function belongs to, in your case the function belongs to the window object or global object, the 'this' keyword behaves differently depending on how you use your function, if you use it as a constructor function for example (with the new keyword) 'this' will be bound to new object being constructed, and when the function is used as an event handler this will be set to the event the element the event fired from.
see :https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this for more information.
you need to change your code and do something like this:
$(".button").on("click",function(){
var $this = $(this) //refers to the event it was fired from (button object)
$(".output").text("You clicked on "+$this.text());
});
i used classes instead of ids to target any button that's clicked
an example in jsfiddle: http://jsfiddle.net/fvacbd9u/

Checking which element is causing the event from a list of elements in Javascript

I have a list of elements with its event listeners like this :
var h1 = document.getElementById("h1"),
h2 = document.getElementById("h2"),
h3 = document.getElementById("h3");
var elemArray = [h1,h2,h3];
for(var i=0;i<elemArray.length;i++){
elemArray[i].addEventListener("click",mouseListener,false);
}
function mouseListener(e){
// code goes here
// whenever it's called i want to know from
// which element it's been called
}
Now what i want is whenever i click on one of the elements,
I want to know which one has been clicked without using different functions for each element.
Just use this variable inside your callback, it will point to the target element:
function mouseListener(e) {
console.log( this.id );
}
function mouseListener(e){
var elementEventWasSet = this;
var clickedEl = e.target; // in case of bubbling, this is the one that was clicked
// code goes here
// whenever it's called i want to know from
// which element it's been called
}
You can do something like this
function mouseListener(e){
if(this === h1){
console.log("First was pressed");
}else if(this === h2){
console.log("Second was pressed");
}else if(this === h3){
console.log("Third was pressed");
}
}
This will work only if h1,h2 and h3 are global variable.
You can see this approach in action on this site:
http://jsfiddle.net/94xMu/2/

Javascript onClick Globally

I have a web application with many forms that submit data to a MySQL Database.
On all pages i have include 'settings.php'; so whatever i put in there will be on every page (CSS Links, JS Code etc)
Whats the best JS Code i can put in my settings.php file to put an "onClick" event on every single button on all pages.
I want it to do this:
onClick="this.disabled=true; this.value='Please Wait…';"
So on all forms within the site, every button that is clicked will display the Please Wait... text until the form is submitted
Clearly most of the people answering this question have never heard of event delegation.
window.addEventListener("click",function(e) {
var t = e.srcElement || e.target;
if( !t.tagName) t = t.parentNode;
if( t.tagName == "INPUT" && t.type.toLowerCase() == "submit") {
t.disabled = true;
t.value = "Please wait...";
}
},false);
You really shouldn't be using onClick=... Instead, bind the actions via JS:
document.getElementById('element-id').onclick=function(){
alert('Hello World');
}
Something like this ought to do it:
(function() {
var buttons = document.getElementsByTagName('button');
for (var i=0,len=buttons.length; i<len; i++) {
buttons[i].addEventListener('click', function() {
this.disabled = true;
this.innerHTML = "Please Wait...";
});
}
})();
http://jsfiddle.net/ryanbrill/5WYN9/
// very simple with jQuery
$(document).on('click', 'button,input[type="button"],input[type="submit"]', function (e) {
var $this = $(this).prop('disabled', true);
if ($this.is('button')) {
$this.html('Please wait...');
} else {
$this.val('Please wait...');
}
});

Jquery: Passing a function to a function which isnt required

So I have a function that submits things through AJAX and then displays a dialog if it was successful or not. All works fine, but then I want the option of passing that dialog function an extra function (optional) which will carry out extra functions.
Here's what I have:
// the work
if (data._response.success == 'true') {
$("#suppliers_grid").trigger("reloadGrid");
$('#manage-suppliers-form').fullFormReset();
alertDialog('Supplier '+ action +' successfully!','Success',$('#manage-suppliers-form :input:visible:first').focus());
} else {
alertDialog('Supplier was not '+ action +' successfully!<br />Please try again or report this to the administrator.','Error','ui-state-error');
}
// the alertDialog function
function alertDialog(message,title,cssClass,closeFunction) {
title = typeof title !== 'undefined' ? title : 'Notice';
cssClass = typeof cssClass !== 'undefined' ? cssClass : 'ui-state-highlight';
if (cssClass=='ui-state-error') {
icon = 'ui-icon-alert';
}
else {
icon = 'ui-icon-info';
}
var dialog = $('<div><p><span class="ui-icon '+ icon +'"></span>'+ message +'</p></div>');
dialog.dialog({
modal: true,
title: title,
buttons: {
Ok: function() { $(this).dialog("close"); }
},
close: closeFunction()
});
}
1) The above doesn't work if I pass a closeFunction
2) Haven't even tested it -without- passing it something, but I'm sure it wouldn't work either. closeFunction should be OPTIONAL
3) I cant simply put the 'focus' line of code after the alertDialog call. Even though this works (gets focus in the background). As soon as someone clicks "ok" on the alertDialog, the focus is lost - so needs to be called on the close of the alertDialog.
First of all, whatever you mentioned in your question (Passing a function to a function) is called as "callback" function in the Javascript programming world.
Btw, to answer your question, I guess you need to bind the close event callback function that gets called when you close the dialog as follows:
var that = this;
dialog.dialog({
close: function( event, ui ) {
if(closeFunction && typeof closeFunction === 'function') {
closeFunction.call(that);
}
}});
Inside the closeFunction, try to do the focus() for the element required.
Try to read this! to get a better understanding on the close event callback usage.
If you still dont get a proper solution from my answer, please post a fiddle or give a better understanding of the problem your facing!
Try
// the work
if (data._response.success == 'true') {
$("#suppliers_grid").trigger("reloadGrid");
$('#manage-suppliers-form').fullFormReset();
//Pass the function as the fourth parameter and create a annonymous function to set the focus
alertDialog('Supplier '+ action +' successfully!', 'Success', '', function(){
$('#manage-suppliers-form :input:visible:first').focus();
});
} else {
alertDialog('Supplier was not '+ action +' successfully!<br />Please try again or report this to the administrator.','Error','ui-state-error');
}
// the alertDialog function
function alertDialog(message,title,cssClass,closeFunction) {
title = typeof title !== 'undefined' ? title : 'Notice';
cssClass = typeof cssClass !== 'undefined' ? cssClass : 'ui-state-highlight';
if (cssClass=='ui-state-error') {
icon = 'ui-icon-alert';
}
else {
icon = 'ui-icon-info';
}
var dialog = $('<div><p><span class="ui-icon '+ icon +'"></span>'+ message +'</p></div>');
dialog.dialog({
modal: true,
title: title,
buttons: {
Ok: function() { $(this).dialog("close"); }
},
close: closeFunction //assign the function reference instead of the return value of the function
});
}

Disable a button after 3 clicks

I have a form, with a button called add rows. I would like to disable this button after user clicks on it thrice.
You could set a click counter on the button, but seeing as it is called "add rows", I suppose you might be able to just count the number of rows, and determine if it should be disabled that way.
bool disabled = true;
$('#add-rows').prop('disabled', disabled);
Replace true with your favourite means of calculating the number of rows.
From the top answer in google Triple Click Event:
$.event.special.tripleclick = {
setup: function(data, namespaces) {
var elem = this, $elem = jQuery(elem);
$elem.bind('click', jQuery.event.special.tripleclick.handler);
},
teardown: function(namespaces) {
var elem = this, $elem = jQuery(elem);
$elem.unbind('click', jQuery.event.special.tripleclick.handler)
},
handler: function(event) {
var elem = this, $elem = jQuery(elem), clicks = $elem.data('clicks') || 0;
clicks += 1;
if ( clicks === 3 ) {
clicks = 0;
// set event type to "tripleclick"
event.type = "tripleclick";
// let jQuery handle the triggering of "tripleclick" event handlers
jQuery.event.handle.apply(this, arguments)
}
$elem.data('clicks', clicks);
}
};
Used like so:
$("#mybutton").bind("tripleclick", function() {
$(this).attr("disabled", "disabled");
}
Note that you'll probably want to use on instead of bind, see What's the difference between `on` and `live` or `bind`?

Categories