May 2017
Intermediate to advanced
448 pages
10h 10m
English
In addition to implicit iteration, jQuery users should be able to rely on chaining behavior. This means that we need to return a jQuery object from all plugin methods, unless the method is clearly intended to retrieve a different piece of information. The returned jQuery object is usually just the one provided as this. If we use .each() to iterate over this, we can just return its result:
(function($) { $.fn.swapClass = function(class1, class2) { return this .each((i, element) => { const $element = $(element); if ($element.hasClass(class1)) { $element .removeClass(class1) .addClass(class2); } else if ($element.hasClass(class2)) { $element .removeClass(class2) .addClass(class1); } }); };})(jQuery);
Read now
Unlock full access