Search code examples
jqueryfunctionoverriding

Override core jQuery functions on Element level


Is it possible to override core jQuery functions on Element level? For example, I want to override the val() function only on one <select> element.

If I do something like this:

var element = $('select');
var old_val = element.val;
element.val = function () {
  console.log('The new val');
  return old_val.apply(this, arguments);
}
element.val(19);

it works as expected, but as soon as I address the same field with a new jQuery instance

var element = $('select');
element.val(19);

it stops working because we have a new instance of the JQuery object. If I fiddle with $.fn.val function, I change that behavior for all objects which support the val function, which is a bit too much for me.

How can I achieve that?


Solution

  • I made this jquery extension for doing just what you're talking about:

    // overrides a method thats supposed to be called on a single node (a method like val)
    $.fn.overrideNodeMethod = function(methodName, action) {
        var originalVal = $.fn[methodName];
        var thisNode = this;
        $.fn[methodName] = function() {
            if (this[0]==thisNode[0]) {
                return action.apply(this, arguments);
            } else {
                return originalVal.apply(this, arguments);
            }
        };
    };
    

    Bonus over Dave's answer - you don't have to pollute the jquery data namespace or worry about someone overwriting that key