0

I know that doing this is possible:

$(document).ready(testing);

function testing(){
    alert('hellow world!');
}

But how would I make something like this work where I want to pass a variable to the function:

 $(document).ready(testing('hey world!'));

function testing(message){
    alert(message);
}
2
  • 1
    That's not a jQuery function, it is simply a JavaScript function within the scope of a jQuery wrapper. Commented Jan 8, 2014 at 18:58
  • In what weird case would you want this? Commented Jan 8, 2014 at 19:11

2 Answers 2

2

You could use Function.prototype.bind but it come with some disadvantages like losing the this reference or the Event object.

$(document).ready(testing.bind(null, 'message')); //First parameter == this;

function testing(msg){
    alert(msg); //Alert message
}

or you can do it like this :

$(document).ready(testing.bind('message'));

function testing(){
    alert(this); //Alert message
}

Fiddle : http://jsfiddle.net/KedKq/1/

Sign up to request clarification or add additional context in comments.

Comments

1

You can use an anonymous function:

$(document).ready(function() {
  testing('hey world!'));
});

function testing(message){
    alert(message);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.