views:

37

answers:

2

Hello, I'm trying to get started with writing a jquery plugin, have been reading tutorials but am stuck at the beginning.. Here's what I have:

(function($) {

  $.fn.testPlugin = function(options) {
    this.each(function() {  
      alert($(this));
    });
  }     
})(jQuery);

I'm calling it with:

$('#id').testPlugin();

It doesn't however get into the this.each function...

Basically I just want to simply get what is being called, in this case, id: id.... and then I'll be doing some stuff with that...

A: 

This is what I use as a template. Works like a charm!

(function($){
  $.fn.extend({
    plugin_name: function(settings){
      var defaults = {
        placeholder : true
      };
      var settings = $.extend(defaults, settings);
      return this.each(function(){
        var s = settings;

        // Code goes here

      });
    }
  });
})(jQuery);
Fred Bergman
Fred, thanks... so I've just tried this, however where the code goes, if I do alert(s.placeholder) and I've updated placeholder to this.. placeholder: 'test', It returns undefined.. I call it like this also $('id').plugin_name({placeholder: 'test'});
Dave
A: 

The code that you posted appears fine. The reason why you are not seeing alert boxes may be that the browser did not finish parsing the HTML document (also called "preparing the DOM") before you called your plug-in.

Try:

$(document).ready(function() {
    $('#id').testPlugin();
});
Daniel Trebbien