6

I have a script and I need to be able to name some of my anonymous click functions. For instance, here is some code:

Document ready:

$(function(){

$('#map').imagemap([
        {top_x: 1,top_y: 2,bottom_x: 290,bottom_y:380,callback: #id1 anonymous function},
        {top_x: 275,top_y: 2,bottom_x: 470,bottom_y:380,callback: #id2 anonymous function},
        {top_x: 460,top_y: 2,bottom_x: 701,bottom_y:380,callback: #id3 anonymous function}
    ]);

$('#id1').click(function() {
    ....
});

$('#id2').click(function() {
    ....
});

$('#id3').click(function() {
    ....
});
...
});

How do I write my callbacks so that I don't have to duplicate the code outside the document.ready? I tried putting it all inline, following the callback:, but it didn't work. So what do I put in place of my anonymous function callback calls?

2
  • are the functions all the same or are they different? Commented Mar 4, 2011 at 17:36
  • They are three different click functions. Commented Mar 4, 2011 at 17:36

3 Answers 3

12

It sounds like you want to have the click functions use a named function which is callable from elsewhere in the code. If so just define the functions outside the jQuery ready function and use them by name in the click method.

function id1Click() { 
  ...
}

...
$(function() {
  $('#id1').click(id1Click);
});
Sign up to request clarification or add additional context in comments.

3 Comments

@shummel7845 - Please make sure you accept @JaredPar's answer (click the checkmark to the left of his answer). This gives him reputation within the community and also helps other people easily find this answer if they have the same question. Thanks!
Why do they make us wait before we can accept? Sometimes that's why I don't accept (or if they don't provide an answer).
@shummel7845 I believe it's an attempt to combat the 'fastest gun in the west' problem. meta.stackexchange.com/questions/9731/…
2

Instead of using an anonymous function like in your example

$('#id3').click(function() {
    ....
});

you can define your function elsewhere and use that function

$('#id3').click(myClickCallback);

function myClickCallback{
 ...
}

Comments

1
function id1_click() { ... }
function id2_click() { ... }
function id3_click() { ... }

$(function(){

$('#map').imagemap([
        {top_x: 1,top_y: 2,bottom_x: 290,bottom_y:380,callback: id1_click },
        {top_x: 275,top_y: 2,bottom_x: 470,bottom_y:380,callback: id2_click },
        {top_x: 460,top_y: 2,bottom_x: 701,bottom_y:380,callback: id3_click }
    ]);

$('#id1').click(id1_click);
$('#id2').click(id2_click);
$('#id3').click(id3_click);
...
});

1 Comment

Thanks for the thorough answer, but Jared beat you to it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.