freshyill
freshyill

Reputation: 393

Click events inside jQuery plugin

I'd like to do something relatively simple with a jQuery plugin. I'm just not totally sure about a click event inside of it.

Here's a simple example that works...

$.fn.testy = function() {
  var testElem = this.find('p');
    testElem.click(function(){
      testElem.addClass('highlighted');
      ^^^^^^^^
   });

};

$("div").testy();

Now, if instead of writing testElem.addClass('highlighted');, I put this.addClass('highlighted');, I would get this error: Uncaught TypeError: Object #<HTMLParagraphElement> has no method 'addClass'

I understand that this refers to jQuery in this context. I'm making it work by just reusing the variable, but that feels wrong. How do I target the thing that I'm clicking?

For example, if I were just writing a script, I'd write something like this:

$('a').click(function(){
  $(this).addClass('active');
});

How could I do that while targeting only the a elements inside the specified element?

Upvotes: 3

Views: 5449

Answers (2)

Meligy
Meligy

Reputation: 36594

Let me explain it in comments:

$.fn.testy = function() {
  // `this` here refers to all `DIV`s as jQuery objects

  var testElem = this.find('p');
  // `testElem` is now collection of all `P`s from all `DIV`s, as jQuery object

  testElem.click(function(){ // <<--
      // Note you are now inside another function
      // This function gets called for each `P`

      // of course you don't want to apply yo all `testElem`, only clicked one
      // `this` inside the new function is the `P` AS DOM Element not jQuery
      var $testP = $(this); // just wrapping one `P` in jQuery object
      // Now you can
      $testP.addClass('highlighted');
      // You didn't need the variable, but for explanation
   }); // <<-- finished click function

   // back to plugin function    
};

Here's an even better example that follows jQuery plugin best practices (allowing chaining by returning each() for the jQuery objects called for your plugin):

http://jsfiddle.net/Meligy/s2wN4/

Upvotes: 5

vher2
vher2

Reputation: 990

Do it like this:

$(this).addClass('highlighted');

Upvotes: 0

Related Questions