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.
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));
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With