All jQuery elements matched by a selector are also objects. This peculiarity can be used to extend plain jQuery elements so that they can implement custom methods. A custom method works only on a particular object and it's not shared among all element's instances (as plugins do). For that reason, custom element methods should be used only when you have to attach a specific action to a specific element.
We can use the jQuery's $.extend()
method for our purpose:
var test = $('#test'); $.extend(test, { move: function() { $(this).animate({ left: $(document).width() - $(this).width() }, 800, 'linear', function() { $(this).animate({ left: 0 }, 800, 'linear'); }); } }); $('#run').click(function() { test.move(); });
The official jQuery's documentation uses the fn
object, but after a couple of tests I noticed that this approach doesn't work. You can see the demo below.