Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAndrew Smalling
37 PointsWhat if myCode() function had arguments...?
I wondered if myCode() function here had arguments.
How would we rewrite this code then?
$(document).ready(myCode)
If we put parenthesis and pass argument, it doesn't work :(
Thanx in advance!
5 Answers
Damien Watson
27,419 PointsMaybe try:
$(document).ready(function() {
myCode(yourArgs);
});
Andrew Smalling
37 PointsThank you, Damien Watson on your answer. But what if I need to use this function many more times than just once - an anonymous function won't be the best decision because we will copy the same function many times. The "ready" method is not the best way showing my answer. Honestly, I have a function passing to $(#checkbox).change(myFunction). And myFunction has 2 arguments but i don't know how to pass them.
Andrew Smalling
37 PointsAny ideas to help me? Will be very appreciated.
Bo Christensen
5,924 Pointsif you want to parse arguments like that you use $( "#checkblox" ).click(myFunction(argument1, argument2) { //function do this }); then find the handler that fits you.
Damien Watson
27,419 PointsHi Andrew, Sorry it's taken so long to get back, hopefully you've figured it by now. I just tried this and it works fine... maybe I'm missing something? Cheers.
function myCode(name) {
alert('Hey there ' + name);
}
$(document).ready(myCode('John'));
Another reuse case based on the above 'checkbox' would be something like this:
<input type="checkbox" id="checkbox" name="checkbox">
function myCode(event) {
var data = event.data;
alert('Hey there ' + data.name + ' age ' + data.age + '.');
}
myObj = {
name : "John",
age : 28
}
$('#checkbox').bind('click',myObj, myCode);