I know CSS has the :first-child and :last-child pseudo classes. But :first-child is a part of CSS 2 and has poor browsers support and :last-child is a part of CSS 3 and that's not worth thinking about using yet. The idea is sound though, so I worked up this JavaScript method of getting the same effect.
One advantage of doing this in JavaScript rather than using CSS is that the classes will change if you reorder the child nodes with more JavaScript. In my case I'm using
Scriptaculous sortables. Or to be more specific, I'm using a
Ruby on Rails helper method to make something sortable through Scriptaculous:
1 <%= sortable_element 'image-list',
2 :constraint => false,
3 :url => { :action => 'sort', :issue_id => params[:issue_id] }
4 -%>
I've chosen to not make this script run unobtrusively. Most of it can go into a file and be included in the header or added to your own common JavaScript include file. To get it to run on a page you will need to include something like the below in each page.
1 <script type="text/javascript">
2 //<![CDATA[
3 Event.onDOMReady(function(){FirstLast.go("image-list")});
4 Ajax.Responders.register({
5 onComplete: function(){FirstLast.go("image-list");}
6 });
7 //]]>
8 </script>
I use the
DOMReady extension for Prototype's Event object, but you can use any loader you want. The Ajax.Responders.register part reruns the script after a drag-and-drop operation (or any Ajax operation really).
Download Scriptaculous and Prototype. 1 var FirstLast = {
2 go: function(el) {
3 el = $(el);
4
5 // Whitespace nodes need to be cleaned to get the intended effect
6 var children = Element.cleanWhitespace(el).childNodes;
7
8 // Return if there are not any children
9 if (0 == children.length) return
10
11 if (1 == children.length) {
12 // Cheap shortcut if there is only 1 child node
13 children[0].addClassName(this._firstChildClassName);
14 children[0].addClassName(this._lastChildClassName);
15 } else {
16 for (var i = 0; i < children.length; i++) {
17 switch (i) {
18 // First child
19 case 0:
20 children[i].addClassName(this._firstChildClassName);
21 children[i].removeClassName(this._lastChildClassName);
22 break;
23 // Last child
24 case children.length - 1:
25 children[i].removeClassName(this._firstChildClassName);
26 children[i].addClassName(this._lastChildClassName);
27 break;
28 // Every child other than the first or last
29 default:
30 children[i].removeClassName(this._firstChildClassName);
31 children[i].removeClassName(this._lastChildClassName);
32 break; // I know it is unnecessary
33 }
34 }
35 }
36 },
37 // Pseudo Private methods and attributes
38 _firstChildClassName: "first",
39 _lastChildClassName: "last"
40 };