Skip to content

Instantly share code, notes, and snippets.

@JustinMorgan
Created January 22, 2017 21:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JustinMorgan/f96ee571f14a2216ca2ee576594265f2 to your computer and use it in GitHub Desktop.
Save JustinMorgan/f96ee571f14a2216ca2ee576594265f2 to your computer and use it in GitHub Desktop.
documentation?("jQuery.fn.order", {
Description: "jQuery plugin for client-side list sorting"
Usage: (foo, selector = null, sortBy = null, options = null) -> [
$(foo).order(selector, sortBy, options)
$(foo).order(selector, sortBy)
$(foo).order(selector, options)
$(foo).order(options)
$(foo).order()
]
Parameters:
selector:
types:
"jQuery selector": String
callback: (index, element) -> Boolean
desc: "which child elements to sort"
default: "sort the current selection in place"
sortBy:
types:
"jQuery selector": String
callback: (element) -> "value"
desc: "how to determine an element's value for the purpose of sorting"
default: (element) -> $(element).text()
options:
types: Object
contents:
selector: "as above"
sortBy: "as above"
caseSensitive:
types: Boolean
desc: "sort by ASCII-case (all of [A-Z] before all of [a-z])"
default: false
ignoreWhitespace:
types: Boolean
desc: "ignore whitespace when sorting"
default: true
})
do ($ = jQuery) ->
$.fn.order = (args...) ->
if args.length <= 2 and typeof args[args.length - 1] in ['object', 'undefined']
[options, selector] = args.reverse()
else
[selector, sortBy, options] = args
options = $.extend {}, $.fn.order.defaults, options
selector ?= options.selector
sortBy ?= options.sortBy
if selector?
parent = this
children = this.children().filter selector
else
parent = this.parent()
children = this
val = (x) ->
vX = sortBy?(x) ? $(x).find(sortBy).text()
if options.ignoreWhitespace
vX = vX?.trim?() ? vX
if !options.caseSensitive
vX = vX?.toLowerCase?() ? vX
parent.prepend children.sort (a, b) ->
if (val a) < (val b) then -1 else 1
$.fn.order.defaults =
sortBy: (x) ->
$(x).text()
caseSensitive: no
ignoreWhitespace: yes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment