Practice Set, Week 12, Well-behaved plugins

by mtzara

HTML

<h3>Practice Set, Week 12, jQuery Collections Plugin</h3>

<p>This page includes a jQuery collections plugin which works, but it is not a very well-behaved plugin.</p>
<p>Your task is to fix it so that it properly supports chaining, and protects the global scope from whatever it does, while also supporting the use of the jQuery.noConflict() setting. These are discussed as steps two and three of the section on having a well-behaved plugin, and are demonstrated in video 12.2.</p>
<p>If you've got it right, you should be able to:</p>
<ol>
    <li>Uncomment line 1, which calls jQuery.noConflict()</li>
    <li>Comment out line 15, which will start throwing an error after you've called .noConflict()</li>
    <li>Uncomment line 17, which uses jQuery by its name rather than the $, and chains jQuery method calls.</li>
</ol>
<p>The output will look the same as initially (with a little 'size' box after each &lt;p&gt;) , except all the &lt;p&gt; text will turn blue.</p>
<p><b>Explanation of the plugin code:</b> This plugin displays the size of any element returned in the jQuery selection. For each element, it creates a span. For convenience, we make 'span' a jQuery object on line 8, and add the 'super' class to it in line 10. Then we add the size information to the span (line 10), and then append the span to the original element (line 11). The CSS causes the size information to be small and have a lightyellow background.</p>

CSS

.super {
    font-size: 75%;
    background-color: lightyellow;
}
.

JavaScript

jQuery.noConflict();   //uncomment this to test your solution

(function($){
// HERE IS THE PLUGIN
$.fn.showSize = function () {
    console.log(this);
    return this.each(function (i, el) {
        var span = document.createElement('span');
        var jqSpan = $(span);
        jqSpan.addClass("super");
        jqSpan.html("size: " + el.clientWidth + "x" + el.clientHeight);
        el.appendChild(jqSpan[0]);
    });
    }
}(jQuery));
// using my plugin - you'll comment this line to test your code
//$('p').showSize();
// uncomment the following line to test your solution
jQuery('p').showSize().addClass("blue");