[jquery] How to run a function in jquery

I'm a programming newbie, and I can't figure out how to 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!

This question is related to jquery function

The answer is


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

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

You can also do this - Since you want one function to be used everywhere, you can do so by directly calling JqueryObject.function(). For example if you want to create your own function to manipulate any CSS on an element:

jQuery.fn.doSomething = function () {
   this.css("position","absolute");
   return this;
}

And the way to call it:

$("#someRandomDiv").doSomething();

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();
});

Is this the most obfuscated solution possible? I don't believe the idea of jQuery was to create code like this.There's also the presumption that we don't want to bubble events, which is probably wrong.

Simple moving doosomething() outside of $(function(){} will cause it to have global scope and keep the code simple/readable.


function doosomething ()
{
  //Doo something
}


$(function () {


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

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

});