Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery: how to name click functions?

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?

like image 768
sehummel Avatar asked Mar 04 '11 17:03

sehummel


2 Answers

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);
});
like image 81
JaredPar Avatar answered Oct 01 '22 08:10

JaredPar


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{
 ...
}
like image 34
Babak Naffas Avatar answered Oct 01 '22 08:10

Babak Naffas