jQuery UI Dialog Auto-Close using setTimeout - javascript

I'm trying to have my dialog auto-close three seconds after opening. I've tried the following methods:
setTimeout($("#mydialog").dialog('close'), 3000);
Here it is in context:
$("#acknowledged-dialog").dialog({
height: 140,
modal: true
});
setTimeout($("#acknowledged-dialog").dialog('close'), 3000);
But with this method, it doesn't even show! I'm guessing the the close method is getting called immediately after it gets shown on the page. The log shows no errors.
I've also tried binding to the dialogopen event:
$("#acknowledged-dialog").bind('dialogopen', function(event, ui) {
setTimeout($(this).dialog('close'), 3000);
});
$("#acknowledged-dialog").dialog({
height: 140,
modal: true
});
The dialog shows, but does not auto-close. No error in the logs here either.
Am I not able to use 'this' in the argument for $ in setTimeout?

setTimeout is calling on the the return value of $("#mydialog").dialog("close") after 3 seconds. you want to throw the whole thing as a string, and it should work just fine. Also, I don't think you want to bind 'dialogopen' before you initialize the dialog. Below should work just fine:
$("#acknowledged-dialog").dialog({
height: 140,
modal: true,
open: function(event, ui){
setTimeout("$('#acknowledged-dialog').dialog('close')",3000);
}
});

I wrote an article specifically for the problem you are experiencing. Please read that.
In short, you want to wrap $("#mydialog").dialog('close') with an inline function everywhere you want it executed as a result of a delay or a triggered event.
setTimeout(function(){
$("#mydialog").dialog('close')
}, 3000);
The dialog doesn't even show because you closed it as soon as you opened it in each case.

Related

Getting wrong length on dialog

I'm working with jquery and I'm trying to listen for how may are there open after I close a dialog, but I'm getting how many where open.
For example: if I have 4 and I close one it returns 4 when I expect to get 3, and at the end when I have only 1 open it returns 2, and at the end the when I close the last one return 1.
Am I doing right? I try look in the docs and try to look for something like afterClose but there is not.
$( ".test" ).dialog({
autoOpen: false,
height: "auto",
width: "auto",
modal: true,
close: function(e){
$(this).destroy();
// This returns wrong lenght
console.log($('.test').length);
if($('.test').length === 1) {
console.log($('.test a').text());
}
}
});
How are you getting those numbers? Unless you are destroying dialogs calling
$('.test').length
is always going to return the number of classes of test on the dom. Are you using .remove() or something to remove the dialogs? More information is needed.
When you close a dialog it does not remove it from the DOM. It just hides it, you can see the hidden html at the bottom of the page. The proper way to use multiple dialogs is to use instances of dialogs. but that shit is complicated. Post some more of your code, specifically how you are setting up your html and if you are some how deleting dialogs.
Also (since i cant comment yet), the close event fires as the window is closing but before the window is hidden, this allows you two places to cancel the close event, beforeClose (typically for some validation), and close (maybe where you do some population of objects or something).
Try changing the jQuery selector to search for visible items:
$( ".test" ).dialog({
autoOpen: false,
height: "auto",
width: "auto",
modal: true,
close: function(e){
// This returns wrong lenght
console.log($('.test:visible').length);
if($('.test:visible').length === 1) {
console.log($('.test a').text());
}
}
});
Source
$( ".test" ).dialog({
autoOpen: false,
height: "auto",
width: "auto",
modal: true,
close: function(e){
$(this).destroy();
// This returns wrong lenght
console.log($('.test').length);
if($('.test').length === 1) {
console.log($('.test a').text());
}
}
});

jQuery scrollTo Plugin Flicker on scroll

I am using the jQuery plugin, scrollTo, to navigate through my webpage. When I click on the button, there seems to be a quick flicker and then resumes to continue scrolling normally. I saw other solutions where they call the preventDefault() method, but I don't know how I would implement it in my case. Here is my method that is called when a link is clicked.
function btn_Pressed(goTo){
$(goTo).ScrollTo({
duration: 1200
});
}
It is a generic method that will scroll to whatever anchor is passed as an argument. What am I doing wrong. THIS FLICKER IS SO UGLY!
I did find a solution, however, I don't know if it is the most efficient one. I made a function that handles each button click so I could explicitly call and handle each scroll all while calling preventDefault(). Here is a sample...
$(function(){
$("#btn_home").click(function(e) {
$('#myAffix').ScrollTo({
duration: 1200,
});
e.preventDefault();
});
$("#aboutUs").click(function(e) {
$('#anchorOne').ScrollTo({
duration: 1200,
});
e.preventDefault();
});
$("#btn_home").click(function(e) {
$('#myAffix').ScrollTo({
duration: 1200,
});
e.preventDefault();
});
});

beforeclose callback of jquery dialog not executed on close

I am trying to make fire a callback on dialog close, and I am unable to debug it from developer tools/firebug. The code defined after beforeclose label is never executed:
$(".dialog").dialog({
autoOpen: false,
modal: true,
width: 300,
beforeclose: function(event, ui)
{
// :input select all buttons, selects, textarea, checkbox
$(':input').removeAttr('checked').removeAttr('selected');
}
});
I get no errors from the console and I searched but no one seems to have the same problem.
I'll show more code if needed.
I'm not sure if it's case sensitive but in the API it's:
beforeClose
Source:
API

How to get the event invoking div with jquery

I have a couple of divs that when clicked opens a fancybox with a textfield that takes a message and then saves the form. This does not work when I want to reuse it, ie using the same function and code for multiple forms. It always pretends to the be first button. And for every time I use it the number of time it runs the callback function increases. Does anyone know what I did wrong? I tried adding the each(), but it did not help.
I'm sorry for the brief explanation, it is a lot clearer when looking at the code (note: I use console.log for the output): http://jsfiddle.net/EvYvc/11/
Basically: I wan't to know what element invoked the click function and get it's attributes.
Couple of changes,
You need to bind the click handler outside beforeShow
I don't think you can identify which reason_submit2 link is clicked inside beforeShow
Alternatively, I defined 2 var's and a click handler for the link which will store the name and form and that will be used later in fancyConfirm_ok
Complete code:
$(function() {
var r2sName = '', r2sForm = '';
$(".reason_submit2").fancybox({
openEffect: 'none',
closeEffect: 'none',
'modal': true
}).click(function () {
var $this = $(this);
r2sName = $this.data("name");
r2sForm = $this.data("form");
});
jQuery(".fancyConfirm_ok").click(function() {
$.fancybox.close();
console.log('form : ' + r2sForm);
console.log('name : ' + r2sName);
console.log('message : ' + $("[name=reason2]").val());
$($(".reason_submit2").data("form")).append($("<input>").attr("type", "hidden").attr("name", "reason").val($("#reason").val()));
$($(".reason_submit2").data("form")).append($("<input>").attr("type", "hidden").attr("name", $(".reason_submit2").data("name")));
//document.forms[$(".reason_submit2").data("form")].submit();
});
});
DEMO
Other trick is to add a class to clicked link inside click handler and use that class to get the name and form inside fancyConfirm_ok, but personally I feel this is better.
I’m no expert in the FancyForm plugin. but I think you are binding the click event multiple times since you are binding it inside the beforeShow handler.
Try binding the click event on it’s own instead:
http://jsfiddle.net/h8sVY/
$(".reason_submit2").each(function() {
$(this).fancybox({
openEffect: 'none',
closeEffect: 'none',
'modal': true
});
});
$(".fancyConfirm_ok").click(function() {
$.fancybox.close();
// etc...
});
​

How to make code wait for okay/cancel button selection?

I am using JQuery's $.dialog(), where I open a dialog with OK and Cancel buttons.
I would have expected that when the dialog opens, the code stops, and would first continue, when the user had selected OK or Cancel.
Here is my complete source code
http://pastebin.com/uw7bvtn7
The section where I have the problem is at line 127-151.
$("#dialog:ui-dialog").dialog("destroy");
$("#dialog-confirm").dialog({
resizable: false,
height: 600,
modal: true,
open: function() {
$(this).children('div.dialog-text').replaceWith("<h3><b>Users</b></h3>" + makeDialogTable(users) + "<h3><b>Owners</b></h3>" + makeDialogTable(owners));
},
buttons: {
"Okay": function() {
$(this).dialog("close");
},
Cancel: function() {
is_okay = 0;
$(this).dialog("close");
}
} // buttons
}); // dialog
alert(is_okay);
What the code does right now is to first show the dialog and then the alert(is_okay) on top.
What I would like is that the code first continues when the user have pressed OK or Cancel.
How could that be done?
You can put your additional code in the "Okay" and "Cancel" button functions. For example:
"Okay": function() {
$(this).dialog("close");
alert(is_okay);
},
That can't be done in a "good" manner plus I strongly recommend not to go that way.
What you describe is a complete blocking, modal window/dialog which is just aweful for web applications. You're already creating the dialog with the modal flag, so a user can't really do anything on your site while the dialog is open, BUT the UI keeps responsive.
Again, there is actually no way to "hold" code execution. Any approach in that direction would freeze the UI thread since Javascript and UI updates share the same thread.
Since quite a few years, developers pushed Javascript to be more and more non-blocking (Javascript in browsers actually always followed that route, which is very good thing). The idea was reborn with nodeJS on the backend. So, you're swimming upstream here, don't do it.
Whatever the problem is you try to solve there, try to think in different way. Think functional, use callbacks and events, think... ECMAscript! :p
The code does execute sequentially. The job of $("#dialog-confirm").dialog() is to popup a dialog box. alert(is_okay) won't execute until the lines above it have been executed. But Okay and Cancel are event listeners.
"Okay": function() {
$(this).dialog("close");
}
The code above assigns event listeners to events. That's all it does, it does not execute those functions, it just assigns those functions to event calls.
I would recommend doing some reading on events and event listeners. If you plan on using JQuery seriously, it will save you a lot of confusion.
$("#dialog-confirm").dialog({ ...
close :(event, ui) { alert(is_okay);}
})
Or you can bind function later :
$( "#dialog-confirm" ).bind( "dialogclose", function(event, ui) {
alert(is_okay);
});
The code doesn't stop and continue like it does with alert , but it will display message only when dialog is closed.
Simply put all code that follows after opening the dialog in a function and call that function from the dialogs callback function for okay / cancel.
function doTheRest(args) {
alert(args);
}
// snippet from dialog options
"Okay": function() {
$(this).dialog("close");
doTheRest(1);
},
"Cancel": function() {
$(this).dialog("close");
doTheRest(0);
}
Browsers use an event-based, asynchronous programming model where many things can (and do) occur at the same time. This is how style-transitions (animations like rolldown or fade) work.
Your example displays a dialog and then throws an alert. It cannot "wait" for the user to click on a button because doing so would stop the browser from doing anything else.
So you'll need to refactor your code to do whatever you require to happen when either the OK or Cancel buttons are clicked within the callback associated with the action.
In other words, you need to:
buttons: {
"Okay": function() { // this function is called when a user clicks the Okay button
// do whatever work is required here
}
}
There is no direct way to "wait" for something in JavaScript -- asynchronous events are generally handled through callbacks. This means you need to think of your program in terms of events and not as sequential code. Instead of your current code:
$("#dialog-confirm").dialog({
...
});
alert(is_okay);
// rest of code
you need to wrap the "rest of code" section into its own function, then call that from the OK/Cancel callbacks of your dialog:
$("#dialog-confirm").dialog({
...
buttons: {
"Okay": function() {
$(this).dialog("close");
what_happens_if_okay();
},
Cancel: function() {
$(this).dialog("close");
what_happens_if_not_okay();
}
} // buttons
}); // dialog
So if I understand correctly you want an alert to show up with the options OK and Cancel and the Dialog would not come up unless OK was hit.
Instead of using another alert why not try using another dialog with Ok and Cancel in it?
In your html do this:
<div id = "hiddenDialogElements">
<button id = "Ok" onclick = "confirm(true)">OK</button>
<button id = "Cancel" onclick = "confirm(false)">Cancel</button>
</div>
With this css:
#hiddenDialogElements
{
display: none;
}
Then you can do this on the event that will create the dialog (Where you want a wait):
$('#hiddenDialogElements').dialog({
//Code
});
And this:
function confirm(ifOk)
{
if(ifOk)
{
//Create Dialog
}else {
//Do nothing
}
}
Do Something Like this ...
function MyAlert(Message, Title,FuncExecAfterOkPressed) {
$("<div>" + Message + "</div>").dialog({
title: Title,
dialogClass: "alert",
width: "auto",
modal:true,
open: function (event, ui) { $(".ui-dialog-titlebar-close").hide(); },
buttons: [
{
text: "Ok", click: function () {
$(this).dialog("close");
if (FuncExecAfterOkPressed != null) {
$.Callbacks().add(FuncExecAfterOkPressed).fire(null);
}
}
}]
});
}
Now Call it like this
MyAlert(data, "Duplicate", function () {
alert("I m moumit");
$("#Name").val("");
});
One thing u need is JQueryUI plugin... Enjoy.

Categories

Resources