Using Progressive Enhancement to skin checkboxes with the help of the YUILoader
and the Event Utility's focus
and blur
events and the
delegate
method.
There are a few challenges when trying to skin an HTML checkbox using CSS. To start, most of the
A-grade browsers don't provide
support for CSS properties like border
and background
on the
<input type="checkbox">
element. Additionally, IE 6 and IE 7 (Quirks Mode)
lack support for attribute selectors — necessary to style the checked
and
disabled
states. Additionally, IE 6 and 7 only support the :focus
and
:active
pseudo classes on <a>
elements, both of which are needed
to style a checkbox when it is focused or depressed.
Despite the shortcomings in cross-browser CSS support, with a little extra markup and through the use of
JavaScript it is possible to skin an <input type="checkbox">
element
consistently well in all of the
A-grade browsers.
Since CSS support for the <input type="checkbox">
element is lacking, wrap
<input type="checkbox">
elements in one or more inline elements to provide the
necessary hooks for styling. In this example, each <input type="checkbox">
element is wrapped by two <span>
s.
1 | <span> |
2 | <span> |
3 | <input type="checkbox"> |
4 | </span> |
5 | </span> |
view plain | print | ? |
To style each checkbox, a class name of yui-checkbox
will be applied to the
outtermost <span>
wrapping each <input type="checkbox">
element. An additional class will be used to represent the various states of each checkbox. The
class name for each state will follow a consistent pattern: yui-checkbox-[state]
.
For this example, the following state-based class names will be used:
yui-checkbox-focus
yui-checkbox-active
yui-checkbox-checked
The styles for each checkbox comes together as follows:
1 | .yui-checkbox { |
2 | |
3 | display: -moz-inline-stack; /* Gecko < 1.9, since it doesn't support "inline-block" */ |
4 | display: inline-block; /* IE, Opera and Webkit, and Gecko 1.9 */ |
5 | width: 10px; |
6 | height: 10px; |
7 | border: inset 2px #999; |
8 | background-color: #fff; /* Need to set a background color or IE won't get mouse events */ |
9 | |
10 | /* |
11 | Necessary for IE 6 (Quirks and Standards Mode) and IE 7 (Quirks Mode), since |
12 | they don't support use of negative margins without relative positioning. |
13 | */ |
14 | |
15 | _position: relative; |
16 | } |
17 | |
18 | .yui-checkbox span { |
19 | |
20 | display: block; |
21 | height: 14px; |
22 | width: 12px; |
23 | overflow: hidden; |
24 | |
25 | /* Position the checkmark for Gecko, Opera and Webkit and IE 7 (Strict Mode). */ |
26 | margin: -5px 0 0 1px; |
27 | |
28 | |
29 | /* Position the checkmark for IE 6 (Strict and Quirks Mode) and IE 7 (Quirks Mode).*/ |
30 | _margin: 0; |
31 | _position: absolute; |
32 | _top: -5px; |
33 | _left: 1px; |
34 | |
35 | } |
36 | |
37 | /* For Gecko < 1.9: Positions the checkbox on the same line as its corresponding label. */ |
38 | .yui-checkbox span:after { |
39 | |
40 | content: "."; |
41 | visibility: hidden; |
42 | line-height: 2; |
43 | |
44 | } |
45 | |
46 | /* |
47 | Hide the actual checkbox offscreen so that it is out of view, but still accessible via |
48 | the keyboard. |
49 | */ |
50 | .yui-checkbox input { |
51 | |
52 | position: absolute; |
53 | left: -10000px; |
54 | |
55 | } |
56 | |
57 | .yui-checkbox-focus { |
58 | |
59 | border-color: #39f; |
60 | background-color: #9cf; |
61 | |
62 | } |
63 | |
64 | .yui-checkbox-active { |
65 | |
66 | background-color: #ccc; |
67 | |
68 | } |
69 | |
70 | .yui-checkbox-checked span { |
71 | |
72 | /* Draw a custom checkmark for the checked state using a background image. */ |
73 | background: url(checkmark.png) no-repeat; |
74 | |
75 | } |
view plain | print | ? |
Application and removal of the state-based class names will be facilitated by JavaScript event
handlers. Each event handler will track the state of the
<input type="checkbox">
element, and apply and remove corresponding
state-based class names from its outtermost <span>
—
making it easy to style each state. And since each JavaScript is required for state management,
the stylesheet for the skinned checkboxes will only be added to the page when JavaScript is
enabled. This will ensure that each checkbox works correctly with and without JavaScript enabled.
Since there could easily be many instances of a skinned checkbox on the page, all event listeners will be attached to the containing element for all checkboxes. Each listener will listen for events as they bubble up from each checkbox. Relying on event bubbling will improve the overall performance of the page by reducing the number of event handlers.
Since the DOM focus
and blur
events do not bubble, use the Event Utility's
specialized focusin
and focusout
events as an alternative to
attaching discrete focus and blur event handlers to the <input type="checkbox">
element of each skinned checkbox. The specialized focusin
and
focusout
events make it possible to attach a single focus and blur event
listener on the containing element of each checkbox — thereby increasing the performance
of the page. The complete script for the example comes together as follows:
1 | (function () { |
2 | |
3 | var Event = YAHOO.util.Event, |
4 | Dom = YAHOO.util.Dom, |
5 | Selector = YAHOO.util.Selector, |
6 | UA = YAHOO.env.ua, |
7 | |
8 | bKeyListenersInitialized = false, |
9 | bMouseListenersInitialized = false, |
10 | sCheckboxFocusClass = "yui-checkbox-focus", |
11 | sCheckboxCheckedClass = "yui-checkbox-checked", |
12 | sCheckboxActiveClass = "yui-checkbox-active", |
13 | forAttr = (UA.ie && UA.ie < 8) ? "htmlFor" : "for", |
14 | bBlockDocumentMouseUp = false, |
15 | bBlockClearActive = false, |
16 | bBlockBlur = false, |
17 | oActiveCheckbox; |
18 | |
19 | |
20 | var initKeyListeners = function () { |
21 | |
22 | Event.delegate(this, "keydown", onCheckboxKeyDown, ".yui-checkbox"); |
23 | Event.delegate(this, "click", onCheckboxClick, ".yui-checkbox"); |
24 | Event.delegate(this, "focusout", onCheckboxBlur, "input[type=checkbox]"); |
25 | |
26 | bKeyListenersInitialized = true; |
27 | |
28 | }; |
29 | |
30 | |
31 | var initMouseListeners = function () { |
32 | |
33 | Event.delegate(this, "mouseover", onCheckboxMouseOver, ".yui-checkbox"); |
34 | Event.delegate(this, "mouseout", onCheckboxMouseOut, ".yui-checkbox-active"); |
35 | Event.on(this.ownerDocument, "mouseup", onDocumentMouseUp); |
36 | |
37 | bMouseListenersInitialized = true; |
38 | |
39 | }; |
40 | |
41 | |
42 | var getCheckbox = function (node) { |
43 | |
44 | return (Dom.hasClass(node, "yui-checkbox") ? node: |
45 | Dom.getAncestorByClassName(node, "yui-checkbox")); |
46 | |
47 | }; |
48 | |
49 | |
50 | var getCheckboxForLabel = function (label) { |
51 | |
52 | var sID = label.getAttribute(forAttr), |
53 | oInput, |
54 | oCheckbox; |
55 | |
56 | if (sID) { |
57 | |
58 | oInput = Dom.get(sID); |
59 | |
60 | if (oInput) { |
61 | oCheckbox = getCheckbox(oInput); |
62 | } |
63 | |
64 | } |
65 | |
66 | return oCheckbox; |
67 | |
68 | }; |
69 | |
70 | |
71 | var updateCheckedState = function (input) { |
72 | |
73 | var oCheckbox = getCheckbox(input); |
74 | |
75 | if (input.checked) { |
76 | Dom.addClass(oCheckbox, sCheckboxCheckedClass); |
77 | } |
78 | else { |
79 | Dom.removeClass(oCheckbox, sCheckboxCheckedClass); |
80 | } |
81 | |
82 | }; |
83 | |
84 | |
85 | var setActiveCheckbox = function (checkbox) { |
86 | |
87 | Dom.addClass(checkbox, sCheckboxActiveClass); |
88 | oActiveCheckbox = checkbox; |
89 | |
90 | }; |
91 | |
92 | |
93 | var clearActiveCheckbox = function () { |
94 | |
95 | if (oActiveCheckbox) { |
96 | Dom.removeClass(oActiveCheckbox, sCheckboxActiveClass); |
97 | oActiveCheckbox = null; |
98 | } |
99 | |
100 | }; |
101 | |
102 | |
103 | var onCheckboxMouseOver = function (event, matchedEl) { |
104 | |
105 | if (oActiveCheckbox === matchedEl) { |
106 | Dom.addClass(oActiveCheckbox, sCheckboxActiveClass); |
107 | } |
108 | |
109 | }; |
110 | |
111 | |
112 | var onCheckboxMouseOut = function (event, matchedEl) { |
113 | |
114 | Dom.removeClass(matchedEl, sCheckboxActiveClass); |
115 | |
116 | }; |
117 | |
118 | |
119 | var onDocumentMouseUp = function (event) { |
120 | |
121 | var oCheckbox; |
122 | |
123 | if (!bBlockDocumentMouseUp) { |
124 | |
125 | oCheckbox = getCheckbox(Event.getTarget(event)); |
126 | |
127 | if ((oCheckbox && oActiveCheckbox !== oCheckbox) || !oCheckbox) { |
128 | clearActiveCheckbox(); |
129 | } |
130 | |
131 | } |
132 | |
133 | bBlockDocumentMouseUp = false; |
134 | |
135 | }; |
136 | |
137 | |
138 | var onCheckboxFocus = function (event, matchedEl, container) { |
139 | |
140 | // Remove the focus style from any checkbox that might still have it |
141 | |
142 | var oCheckbox = Selector.query(".yui-checkbox-focus", "checkboxes", true); |
143 | |
144 | if (oCheckbox) { |
145 | Dom.removeClass(oCheckbox, sCheckboxFocusClass); |
146 | } |
147 | |
148 | |
149 | // Defer adding key-related and click event listeners until |
150 | // one of the checkboxes is initially focused. |
151 | |
152 | if (!bKeyListenersInitialized) { |
153 | initKeyListeners.call(container); |
154 | } |
155 | |
156 | oCheckbox = getCheckbox(matchedEl); |
157 | |
158 | Dom.addClass(oCheckbox, sCheckboxFocusClass); |
159 | |
160 | }; |
161 | |
162 | |
163 | var onCheckboxBlur = function (event, matchedEl) { |
164 | |
165 | if (bBlockBlur) { |
166 | bBlockBlur = false; |
167 | return; |
168 | } |
169 | |
170 | var oCheckbox = getCheckbox(matchedEl); |
171 | |
172 | Dom.removeClass(oCheckbox, sCheckboxFocusClass); |
173 | |
174 | if (!bBlockClearActive && oCheckbox === oActiveCheckbox) { |
175 | clearActiveCheckbox(); |
176 | } |
177 | |
178 | bBlockClearActive = false; |
179 | |
180 | }; |
181 | |
182 | |
183 | var onCheckboxMouseDown = function (event, matchedEl, container) { |
184 | |
185 | // Defer adding mouse-related and click event listeners until |
186 | // the user mouses down on one of the checkboxes. |
187 | |
188 | if (!bMouseListenersInitialized) { |
189 | initMouseListeners.call(container); |
190 | } |
191 | |
192 | var oCheckbox, |
193 | oInput; |
194 | |
195 | |
196 | if (matchedEl.nodeName.toLowerCase() === "label") { |
197 | |
198 | // If the target of the event was the checkbox's label element, the |
199 | // label will dispatch a click event to the checkbox, meaning the |
200 | // "onCheckboxClick" handler will be called twice. For that reason |
201 | // it is necessary to block the "onDocumentMouseUp" handler from |
202 | // clearing the active state, so that a reference to the active |
203 | // checkbox still exists the second time the "onCheckboxClick" |
204 | // handler is called. |
205 | |
206 | bBlockDocumentMouseUp = true; |
207 | |
208 | // When the user clicks the label instead of the checkbox itself, |
209 | // the checkbox will be blurred if it has focus. Since the |
210 | // "onCheckboxBlur" handler clears the active state it is |
211 | // necessary to block the clearing of the active state when the |
212 | // label is clicked instead of the checkbox itself. |
213 | |
214 | bBlockClearActive = true; |
215 | |
216 | oCheckbox = getCheckboxForLabel(matchedEl); |
217 | |
218 | } |
219 | else { |
220 | |
221 | oCheckbox = matchedEl; |
222 | |
223 | } |
224 | |
225 | // Need to focus the input manually for two reasons: |
226 | // 1) Mousing down on a label in Webkit doesn't focus its |
227 | // associated checkbox |
228 | // 2) By default checkboxes are focused when the user mouses |
229 | // down on them. However, since the actually checkbox is |
230 | // obscurred by the two span elements that are used to |
231 | // style it, the checkbox wont' receive focus as it was |
232 | // never the actual target of the mousedown event. |
233 | |
234 | oInput = Selector.query("input", oCheckbox, true); |
235 | |
236 | // Calling Event.preventDefault won't block the blurring of the |
237 | // currently focused element in IE, so we'll use the "bBlockBlur" |
238 | // variable to stop the code in the blur event handler |
239 | // from executing. |
240 | |
241 | bBlockBlur = (UA.ie && document.activeElement == oInput); |
242 | |
243 | oInput.focus(); |
244 | |
245 | setActiveCheckbox(oCheckbox); |
246 | |
247 | // Need to call preventDefault because by default mousing down on |
248 | // an element will blur the element in the document that currently |
249 | // has focus--in this case, the input element that was |
250 | // just focused. |
251 | |
252 | Event.preventDefault(event); |
253 | |
254 | }; |
255 | |
256 | |
257 | var onCheckboxClick = function (event, matchedEl) { |
258 | |
259 | var oTarget = Event.getTarget(event), |
260 | oInput; |
261 | |
262 | |
263 | if (matchedEl === oActiveCheckbox) { |
264 | |
265 | oInput = Selector.query("input", matchedEl, true); |
266 | |
267 | if (oTarget !== oInput) { |
268 | |
269 | // If the click event was fired via the mouse the checked |
270 | // state will have to be manually updated since the input |
271 | // is hidden offscreen and therefore couldn't be the |
272 | // target of the click. |
273 | |
274 | oInput.checked = (!oInput.checked); |
275 | |
276 | } |
277 | |
278 | updateCheckedState(oInput); |
279 | clearActiveCheckbox(); |
280 | |
281 | } |
282 | |
283 | }; |
284 | |
285 | |
286 | var onCheckboxKeyDown = function (event, matchedEl) { |
287 | |
288 | // Style the checkbox as being active when the user presses the |
289 | // space bar |
290 | |
291 | if (Event.getCharCode(event) === 32) { |
292 | setActiveCheckbox(matchedEl); |
293 | } |
294 | |
295 | }; |
296 | |
297 | |
298 | var checkboxes = Selector.query("#checkboxes>div>span"); |
299 | |
300 | for (var i = checkboxes.length - 1; i >= 0; i--) { |
301 | Dom.addClass(checkboxes[i], "yui-checkbox"); |
302 | } |
303 | |
304 | // Remove the "yui-checkboxes-loading" class used to hide the |
305 | // checkboxes now that the checkboxes have been skinned. |
306 | |
307 | document.documentElement.className = ""; |
308 | |
309 | |
310 | // Add the minimum number of event listeners needed to start, bind the |
311 | // rest when needed |
312 | |
313 | Event.delegate("checkboxes", "mousedown", onCheckboxMouseDown, ".yui-checkbox,label"); |
314 | Event.delegate("checkboxes", "focusin", onCheckboxFocus, "input[type=checkbox]"); |
315 | |
316 | }()); |
view plain | print | ? |
The markup above will be transformed using both CSS and JavaScript. To account
for the scenario where the user has CSS enabled in their browser but JavaScript
is disabled, the CSS used to style the checkboxes will be loaded via JavaScript
using the
YUI Loader.
Additionally, a small block of JavaScript will be placed in the
<head>
— used to temporarily hide the markup
while the JavaScript and CSS are in the process of loading to prevent the user
from seeing a flash unstyled content.
1 | (function () { |
2 | |
3 | // Use the YUILoader to load the JavaScript and CSS required for |
4 | // skinning the checkboxes. |
5 | |
6 | var loader = new YAHOO.util.YUILoader({ |
7 | |
8 | require: ["event-delegate"], |
9 | loadOptional: true, |
10 | base: '../../build/', |
11 | timeout: 10000, |
12 | onFailure: function () { |
13 | |
14 | // Show the checkboxes if the loader failed that way the original |
15 | // unskinned checkboxes will be visible so that the user can |
16 | // interact with them either way. |
17 | |
18 | document.documentElement.className = ""; |
19 | |
20 | } |
21 | |
22 | }); |
23 | |
24 | loader.addModule({ |
25 | name: 'checkboxstyles', |
26 | type: 'css', |
27 | varName: "CheckboxCSS", |
28 | fullpath: 'assets/checkbox.css' |
29 | }); |
30 | |
31 | loader.addModule({ |
32 | name: 'checkboxjs', |
33 | type: 'js', |
34 | varName: "CheckboxJS", |
35 | fullpath: 'assets/checkbox.js' |
36 | }); |
37 | |
38 | loader.require(["checkboxstyles", "checkboxjs"]); |
39 | |
40 | loader.insert(); |
41 | |
42 | }()); |
view plain | print | ? |
You can load the necessary JavaScript and CSS for this example from Yahoo's servers. Click here to load the YUI Dependency Configurator with all of this example's dependencies preconfigured.
Note: Logging and debugging is currently turned off for this example.
Copyright © 2011 Yahoo! Inc. All rights reserved.
Privacy Policy - Terms of Service - Copyright Policy - Job Openings