views:

2456

answers:

4

I'm a programming newbie and I can't figure out store a function in jquery and run in it multiple places.

I have:

$(function () {
  $("div.class").click(function(){
    //Doo something

  });

  $("div.secondclass").click(function(){
    //Doo something
  });

});

Now the 2 //Doo somethings are the same, and I don't want to write the same code again.

If I put

$(function () {

  function doosomething ()
  {
    //Doo something
  }

  $("div.class").click(doosomething);

  $("div.secondclass").click(doosomething);

});

That would run the function on page load, rather than only when it clicks.

How do I do this correctly?

Thanks!

+1  A: 

The following should work nicely.

$(function() {

  // Way 1
  function doosomething()
  {
    //Doo something
  }

  // Way 2, equivalent to Way 1
  var doosomething = function() {
    // Doo something
  }

  $("div.class").click(doosomething);

  $("div.secondclass").click(doosomething);

});

Basically, you are declaring your function in the same scope as your are using it (JavaScript uses Closures to determine scope).

Now, since functions in JavaScript behave like any other object, you can simply assign doosomething as the function to call on click by using .click(doosomething);

Your function will not execute until you call it using doosomething() (doosomething without the () refers to the function but doesn't call it) or another function calls in (in this case, the click handler).

Andrew Moore
Thank you for way 2, I'll have to try that. But the function is indeed ran on page load because in jquery $(function() is shorthand for document load. So way 1 at least, will not work.
Corin
Way 1 does work... I just tested it.
Andrew Moore
+1  A: 
function doosomething ()
{
  //Doo something
}


$(function () {


  $("div.class").click(doosomething);

  $("div.secondclass").click(doosomething);

});
Vincent Ramdhanie
+4  A: 

Alternatively (I'd say preferably), you can do it like this:

$(function () {
  $("div.class, div.secondclass").click(function(){
    //Doo something
  });
});
cpharmston
+1: Very true...
Andrew Moore
That defeats the point of the question.
Corin
A: 

I would do it this way:

(function($) {
jQuery.fn.doSomething = function() {
   return this.each(function() {
      var $this = $(this);

      $this.click(function(event) {
         event.preventDefault();
         // Your function goes here
      });
   });
};
})(jQuery);

Then on document ready you can do stuff like this:

$(document).ready(function() {
   $('#div1').doSomething();
   $('#div2').doSomething();
});
noboruwatanabe