Skip to content

Instantly share code, notes, and snippets.

@srph
Last active April 28, 2017 05:20
Show Gist options
  • Select an option

  • Save srph/e5e323564a84364b483183812238faa9 to your computer and use it in GitHub Desktop.

Select an option

Save srph/e5e323564a84364b483183812238faa9 to your computer and use it in GitHub Desktop.
jQuery: Add sorting to a column

data-jort

Add sorting to a column

usage

<th data-jort="first_name">

how it works

It sets the sort query parameter to ascending (first_name), descending (-first_name), and then deletes it.

example template

This example uses Blade (Laravel's Templating Engine) to display the sorting

@if($sort === 'last_name')
  <span class="dropup">
    <span class="caret"></span>
  </span>
@elseif ($sort === '-last_name')
  <span class="caret"></span>
@endif
+(function($) {
$('[data-jort]').on('click', function() {
var el = $(this)
var key = el.data('jort')
var q = new URLSearchParams(window.location.search)
var sort = q.get('sort')
var descending = `-${key}`
if (!sort || (sort !== key && sort !== descending)) {
q.set('sort', key)
} else if (sort.substr(0, 1) === '-') {
q.delete('sort')
} else {
q.set('sort', descending)
}
window.location.search = String(q)
})
})(jQuery)
[data-jort] {
cursor: pointer;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment