0

I have the following code that I apply when the document is ready:

$(document).ready(function () {
 $('#updateDialog').dialog({
 autoOpen: false,
 width: 400,
 resizable: false,
 modal: true,
 buttons: {
 "Update": function () {
 $("#update-message").html(''); //make sure there is nothing on the message before we continue 
 $("#updateReferenceForm").submit();
 },
 "Cancel": function () {
 $(this).dialog("close");
 }
 }
 });
 });

Is there a way that I can take the actions of this code and move it to a function. Then just have a one line call to this function inside my $(document).ready(function () {

asked Jan 17, 2012 at 10:40
0

2 Answers 2

5

Yes it's very simple:

function foo()
{
 $('#updateDialog').dialog({
 autoOpen: false,
 width: 400,
 resizable: false,
 modal: true,
 buttons: {
 "Update": function () {
 $("#update-message").html(''); //make sure there is nothing on the message before we continue 
 $("#updateReferenceForm").submit();
 },
 "Cancel": function () {
 $(this).dialog("close");
 }
 }
 }); 
}
// First way:
$(function(){
 foo();
});
// Second way:
$(document).ready(function () {
 foo()
});
// Mathias Bynens version to save conflicts with global vars.
(function() {
 var foo = function() { /* do something */};
 $(foo); 
 }()
 );
answered Jan 17, 2012 at 10:41
Sign up to request clarification or add additional context in comments.

13 Comments

Even shorter: $(foo). Note for OP. When the jQuery constructor is called with a function as an argument, its short for $(document).ready(foo);.
This will create a global variable (foo), which is something that should be avoided.
@RobW, Didn't finished editing the answer, I added it later... =)
@MathiasBynens. He can call the function anything he wants, I can't choose a name that fits to some unknown application...
@gdoron It’s not about the variable name foo, it’s about polluting the global namespace in general. It would be better to add this to the global jQuery object instead.
|
1

Sure, use this sample:

$(document).ready(function() {
 MyBlah("hello");
});
function MyBlah(blah) {
 alert(blah);
}
answered Jan 17, 2012 at 10:43

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.