Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use the attr() function inside a new plugin?

I want to know if it's possible to use the attr() function inside a new plugin :

(function ($) {
     $.fn.resetColor = function() {
        var oldColor=this.attr("memColor");
        this.css('background-color',oldColor);
     };
})(jQuery);

I've tried the code above but it doesn't work. I'm sure the memColor attribute exists because I've tested it with an alert in the $(document).ready block.

like image 826
Neo Avatar asked Dec 15 '14 00:12

Neo


1 Answers

The jQuery plugin authoring guidelines recommend this method:

(function ($) {
     $.fn.resetColor = function() {
         return this.each(function() {
            var elem = $( this );

            var oldColor = elem.attr("memColor");
            elem.css('background-color',oldColor);
         };
     });
}(jQuery));
  1. Assume the plugin is called on a set of elements.
  2. Obtain the jQuery wrapped element to work with.

Also be aware that there is a difference between properties (prop()) and attributes (attr()), the former refers to properties on JavaScript DOM HTMLElements, while the later refers to HTML attributes as they are specified in the markup. And jQuery makes this distinction also starting with version 1.6:

The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.


Demo:

    (function ($) {
         $.fn.resetColor = function() {
             return this.each(function() {
                var elem = $( this );

                var oldColor = elem.attr("memColor");
                elem.css('background-color',oldColor);
             });
         };
    $('.me').resetColor();
    }(jQuery));
    
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="me" memColor="Red">Lorem ipsum.</div>
<div class="me" memColor="Blue">Lorem ipsum.</div>
like image 95
Alin Purcaru Avatar answered Nov 01 '22 19:11

Alin Purcaru