0

I have made a js function named draw(), now is it possible that I can call this method using . operator after I get the element using $(...). I mean I like this to work $(#myId).draw(). Right now it gives error like undefined function. How can I make it work?

user2864740
  • 60,010
  • 15
  • 145
  • 220
Harry Joy
  • 58,650
  • 30
  • 162
  • 207
  • Are you looking for invoking the method like a jquery function? – RaviH Feb 11 '14 at 06:04
  • @RaviH : yes, just like default methods. – Harry Joy Feb 11 '14 at 06:05
  • Then read about how to write a jquery plugin and make it a jquery plugin. – RaviH Feb 11 '14 at 06:05
  • @WesleyMurch yes it seems duplicate though I am not making any plugin :P. I will mark it as. – Harry Joy Feb 11 '14 at 06:10
  • The `.` operator is not directly related to "invoking functions", excepting as it can affect the context. `$(..).draw()` simple tries to invoke the function-object returned from the `draw` property of the jQuery object which was returned by `$(..)`.. in your case, the property doesn't exist and yields `undefined` which cause the exception to be thrown. The correct way to implement such a feature in this case, as pointed out, is to create a jQuery plugin or "extension". – user2864740 Feb 11 '14 at 06:10

5 Answers5

3

It's hard to tell from your question, but it sounds like you want to create a jQuery plugin. You can do that by extending $.fn:

$.fn.draw = function(){
    /* ... */
}

Then you can call that against a selector:

$('#myId').draw();

More documentation here: http://learn.jquery.com/plugins/basic-plugin-creation/

Ethan Brown
  • 26,892
  • 4
  • 80
  • 92
1

You have to create it as a jquery plugin. As described here.

Best Way to Extend a jQuery Plugin

Documentation from jQuery: http://api.jquery.com/jquery.fn.extend/

JsFiddle sample: http://jsfiddle.net/Wdx75/

var obj1 = { "color" : "yellow" };
var obj2 = { "background" : "blue" };

var o = $.extend({}, obj1, obj2);


$.fn.draw = function(){
    $("div").css(o);
}

$('abc').draw();
Community
  • 1
  • 1
drhanlau
  • 2,517
  • 2
  • 24
  • 42
1

You'll neet to look at adding a jquery plugin

$.fn.draw= function(){

}
Community
  • 1
  • 1
actual_kangaroo
  • 5,971
  • 2
  • 31
  • 45
1

The best way is to add methods using jquery.fn.extend ( As we can add several plugin functions at a time )

Sample code looks like

jQuery.fn.extend({
  draw: function() {
    return this.each(function() {
      // add code here to draw
    });
  }
});

Once you add this method, you can use below code to call your draw method on any jQuery element

$("#myId").draw()

Official Reference: jquery.fn.extend

1

You want to use jQuery.fn.extend, documented here http://api.jquery.com/jquery.fn.extend/.

$.fn.extend({
    draw: function() {

    // do something to the jQuery object
    return this;

    }
});

Now you can call .draw on a jQuery object created with $(...).

danasilver
  • 556
  • 3
  • 10