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
Samantha J T Star
33.1k89 gold badges259 silver badges443 bronze badges
2 Answers 2
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
gdoron
151k59 gold badges302 silver badges376 bronze badges
Sign up to request clarification or add additional context in comments.
13 Comments
Rob W
Even shorter:
$(foo). Note for OP. When the jQuery constructor is called with a function as an argument, its short for $(document).ready(foo);.Mathias Bynens
This will create a global variable (
foo), which is something that should be avoided.gdoron
@RobW, Didn't finished editing the answer, I added it later... =)
gdoron
@MathiasBynens. He can call the function anything he wants, I can't choose a name that fits to some unknown application...
Mathias Bynens
@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. |
Sure, use this sample:
$(document).ready(function() {
MyBlah("hello");
});
function MyBlah(blah) {
alert(blah);
}
Comments
lang-js