2

I check the jQuery plugin site, which teach me how to write a basic plugin:

(function( $ ){
  $.fn.maxHeight = function() {
    var max = 0;
    this.each(function() {
      max = Math.max( max, $(this).height() );
    });
    return max;
  };
})( jQuery );

Then, the div can have the maxHeight method, like this:

var tallest = $('div').maxHeight(); // Returns the height of the tallest div

But I would like to only textarea have maxHeight function, but not the div. How can I do so?

1
  • What do you want to happen when you try and use it on a div? Commented Dec 15, 2011 at 11:50

2 Answers 2

1

You could do...

this.filter('textarea')

If you do an each() on the returned set, it will only iterate over selected textarea elements.

Sign up to request clarification or add additional context in comments.

Comments

0

Check to make sure the element is a textarea before checking/saving the height.

this.each(function() {
    if(this.tagName.toLowerCase() === "textarea") {
        max = Math.max( max, $(this).height() );
    }
});

jQuery plugins don't give functions to certain elements, they give functions to the jQuery object for working with a set of selected elements. The best solution would be to keep them as generic as possible and only call $("textarea").maxHeight() when you need it. You aren't doing anything specific to textareas in the plugin and if you leave it as it is now, you don't need to make a change to it in the future if $('div').maxHeight() becomes a required use-case.

2 Comments

You can use is('textarea').
This is the same thing, but without the overhead of the Sizzle parser.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.