Arjun Raj
Arjun Raj

Reputation: 984

jQuery custom function to javascript

I recently write this in jQuery

$.fn.my_cus_fn = function(){
    $(this.selector).click(function(e) {
        // do stuff
    });
    $(this.selector).focus(function(e) {
        // do stuff
    });
    // ................    
}

Then I used it like.

$('#my_action1').my_cus_fn();
$('.my_action2').my_cus_fn();

I wanted to write it using javascript only.

I didn't find any solutin for it. Can anyone help me?

Expecting something like

document.getElementById('my_action1').my_cus_fn();

Upvotes: 3

Views: 85

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074148

You can extend the prototype of elements on nearly all browsers (even IE8, and I think it's all modern ones; doesn't work on IE6, not sure about IE7, but those are dead now anyway). Like this:

var ElementConstructor = window.Element || window.HTMLElement;
ElementConstructor.prototype.my_cus_fn = function() {
    // Your code here
};

The Prototype library does this (it's how it got its name). Just beware that you could conflict with other people doing it, and/or with new features added to elements by newer specs. So I'd probably use some kind of likely-to-be-unique prefix on your function names. (FWIW, some years back before significant development on Prototype ended I know the then-maintainers were seriously thinking of not doing prototype extension anymore in favor of wrapping instead, the way jQuery does.)

Complete Example:

<div id="foo">This is the element</div>
<script>
  (function() {
    "use strict";

    var ElementConstructor = window.Element || window.HTMLElement;
    ElementConstructor.prototype.my_cus_fn = function() {
      this.style.color = "green";
    };

    document.getElementById("foo").my_cus_fn();
  })();
</script>

If you're going to do a number of extensions, I'd probably wrap them in a scoping function like this, and give the functions proper names (because of the IE8 problem with named function expressions, I use function declarations):

(function(ctor) {
    var p = ctor.prototype;

    p.my_cus_fn = my_cus_fn;
    function my_cus_fn() { /* ... */ }

    p.my_other_fn = my_other_fn;
    function my_other_fn() { /* ... */ }

})(window.Element || window.HTMLElement);

Upvotes: 3

Related Questions