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 trial

CSS jQuery Basics (2014) Creating a Simple Lightbox Perform: Part 1

Saichand Pullepu
Saichand Pullepu
11,905 Points

JQuery click method using Named function

I want to use named Function for click event instead of anonymous function. Its works OK if I don't pass event. I want to pass event as a parameter to the named function. It doesn't seem to be working..Any help will be appreciated. I know that I cant use parenthesis when calling named functions in jquery but in this case I have to pass event parameter..How? Check the following code:

function getImageLocation(event){ event.preventDefault(); var href = $(this).attr("href"); console.log(href); }

$("#imageGallery a").click(getImageLocation(event));

2 Answers

Colin Bell
Colin Bell
29,679 Points

You're already passing the event parameter in the named function.

Using:

function getImageLocation(event){ 
  event.preventDefault(); 
  var href = $(this).attr("href"); 
  console.log(href); 
}

$("#imageGallery a").click(getImageLocation);

should work for what you're trying to do.

However, if there was a case where you absolutely needed to pass parameters through, I found this solution on stackOverflow

// say your selector and click handler looks something like this...
$("some selector").click({param1: "Hello", param2: "World"}, cool_function);

// in your function, just grab the event object and go crazy...
function cool_function(event){
    alert(event.data.param1);
    alert(event.data.param2);
}
Saichand Pullepu
Saichand Pullepu
11,905 Points

Hi Colin,

Thanks for the answer..