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 trialPresley Cobb
9,214 PointsHow do you create a function that has parameters and then pass that function in a jQuery method?
So im trying to apply what Ive learned here to a small project I have for work. Long story short I can create a function and pass the function easy but if I create a function like lets say something like this:
function add(a, b){
return a + b;
}
I cant figure out how to pass this function into the click method. Passing a method without arguments was shown in the video that's easy but I need to pass this method two arguments but im either unclear on the syntax or jQuery doesnt seem to have this ability built in already.
Thanks for any help you can provide.
2 Answers
Unsubscribed User
8,841 PointsThe add function will return the answer '5' when you click on the paragraph tag. If you click on the bold tag or anywhere in the document, it wont appear. I guess so this is what expected by your question.
<script>
var a,b,c;
function add(a, b) {
c = a + b;
return c;
}
$(document).ready(function(){
$("p").click(function(){
alert(add(2,3));
});
});
</script>
</head>
<body>
<p>If you click on me, alert will appear.</p>
<b>Click me </b>
<b>Click me too!</b>
</body>
jobbol
Full Stack JavaScript Techdegree Student 17,885 PointsSounds like a scoping issue. Posting your workspace would help us figure this out. Anytime a function is created, JS creates a new scope. The rules of scoping are as follows:
*Each scope can access its own variables and variables of the parent.
*Scopes can't access children, and siblings.
Confused? Here's a visual example.
(function(){
var a = 1;
(function(){
var b = 2;
(function(){
var c = 3;
console.log(a,b,c,d); //1, 2, 3, undef
})();
(function(){
var d = 4;
console.log(a,b,c,d); //1, 2, undef, 4
})();
console.log(a,b,c,d); //1, 2, undef, undef
})();
console.log(a,b,c,d); //1, undef, undef, undef
})();
Make sure your add function is declared in the same or a parent scope from your click function.
Chyno Deluxe
16,936 PointsChyno Deluxe
16,936 Points//Changed Comment to Answer