Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery $(this) inside a plugin function

I have this jQuery plugin:

$.fn.touchBind = function(func) {
  $(this).live('touchmove', function() {
    $(this).addClass('dragged');
  });

  $(this).live('touchend', function() {
    if ($(this).hasClass('dragged') == false) {
      func();
    }
  });

  return this;
}

and call it like so:

$('.the-element').touchBind(function() {
  $(this).hide();
});

My problem is that $(this) in $(this).hide() doesn't refer to $('.the-element'), but rather DOMWindow. Is there a way I can make this work?

like image 663
clem Avatar asked Nov 18 '11 00:11

clem


People also ask

What is FN in jQuery?

fn is an alias for jQuery. prototype which allows you to extend jQuery with your own functions. For Example: $.fn.

What do you mean by jQuery how a plugin is used in jQuery?

A jQuery plugin is simply a new method that we use to extend jQuery's prototype object. By extending the prototype object you enable all jQuery objects to inherit any methods that you add. As established, whenever you call jQuery() you're creating a new jQuery object, with all of jQuery's methods inherited.

Is not defined in jQuery?

You may experience the “jQuery is not defined error” when jQuery is included but not loaded. Make sure that it's loaded by finding the script source and pasting the URL in a new browser or tab. The snippet of text you should look for to find the URL to test.


1 Answers

Change func(); to func.call(this); or $.proxy(func, this)();.

You could also use apply() (not necessary when call() suits) or bind() (limited browser support, $.proxy() does essentially the same thing).

like image 129
alex Avatar answered Oct 01 '22 02:10

alex