Skip to content

Instantly share code, notes, and snippets.

@simenbrekken
Created June 25, 2013 07:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simenbrekken/5856670 to your computer and use it in GitHub Desktop.
Save simenbrekken/5856670 to your computer and use it in GitHub Desktop.
Various jQuery convenience plugins
$.fn.template = function(selector) {
return $(this).find(selector + '[data-template]').removeAttr('data-template').remove()
}
$.fn.rows = function(columns) {
var children = $(this).children().get()
while (children.length) {
var chunk = children.splice(0, columns)
$(chunk).wrapAll('<div class="row' + (chunk.length % 2 ? ' uneven' : '') + '">')
}
}
$.fn.date = function(value, format) {
return $(this).each(function() {
return $(this).text(moment(value).format(format))
})
}
$.fn.number = function() {
var value = accounting.formatNumber.apply(null, arguments)
return $(this).each(function() {
var $target = $(this)
$target.is(':input') ? $target.val(value) : $target.text(value)
})
}
$.fn.money = function() {
var value = accounting.formatMoney.apply(null, arguments)
return $(this).each(function() {
return $(this).text(value)
})
}
$.fn.field = function(name, value) {
var $field = $(this).find('[name="' + name + '"]')
if (value !== undefined) {
return $field.val(value)
}
return $.trim($field.val())
}
$.fn.radio = function(name, value) {
var $options = $(this).find('[name="' + name + '"]')
if (value !== undefined) {
return $options.prop('checked', function() {
return $(this).attr('value') == value
})
}
return $options.filter(':checked').attr('name')
}
$.fn.tooltip = (function() {
var $window = $(window),
$body = $(document.body),
$template = $('<div class="tooltip"></div>')
var defaults = {
showDelay: 250,
hideDelay: 2000,
removeDelay: 500,
offsetTop: 10
}
return function(text, options) {
options = _.defaults({}, options, defaults)
var $target = $(this),
$tooltip = $template.clone()
var interval
function show() {
$tooltip.addClass('is-showing')
$body.on('mousedown touchstart keydown', hide)
$window.on('resize', move)
move()
if (options.hideDelay > 0) {
interval = setTimeout(hide, options.showDelay + options.hideDelay)
}
}
// TODO: This is a bit jittery in iOS
function move() {
var offset = $target.offset()
offset.top -= $tooltip.outerHeight() + options.offsetTop
offset.left += ($target.outerWidth() - $tooltip.outerWidth()) * 0.5
$tooltip.offset(offset)
}
function hide() {
$tooltip.removeClass('is-showing').addClass('is-hiding')
$body.off('mousedown touchstart keydown', hide)
clearInterval(interval)
setTimeout(remove, options.removeDelay)
}
function remove() {
$tooltip.remove()
$window.off('resize', move)
}
$tooltip.text(text)
$tooltip.insertAfter($target)
interval = setTimeout(show, options.showDelay)
return $tooltip
}
}())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment