Last active
August 29, 2015 14:06
-
-
Save turboMaCk/fc67bb0018da889b4f8f to your computer and use it in GitHub Desktop.
jQuery input resetable plugin prototype
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function() { | |
var InputResetable = function(element, defaultValue) { | |
this.element = element; | |
this.init(defaultValue); | |
}; | |
InputResetable.prototype = { | |
init: function(defaultValue) { | |
// set default value | |
defaultValue = defaultValue || $(this.element).val(); | |
// value has to be string | |
defaultValue += ''; | |
// build html elements | |
this.build_html(); | |
// event handling | |
var input = this.element; | |
this.$resetBtn.on('click', function(e) { | |
e.preventDefault(); | |
$(input).val(defaultValue) | |
.trigger('focus'); | |
}); | |
}, | |
build_html: function() { | |
// wrap element | |
var $wraper = $(this.element).wrap('<div class="input-resetable-wrapper" />') | |
.parent() | |
.css({ | |
position: 'relative' | |
}); | |
// create reset btn | |
this.$resetBtn = $(document.createElement('a')) | |
.attr('href', '#') | |
.addClass('input-reset-btn') | |
.text('✕') | |
.css({ | |
position: 'absolute', | |
right: 0, | |
padding: '0 15px', | |
display: 'block', | |
color: 'black', | |
top: 0, | |
bottom: 0, | |
'line-height': function() { | |
return $wraper.outerHeight() + 'px'; | |
} | |
}); | |
// add reset btn | |
$wraper.append(this.$resetBtn); | |
} | |
}; | |
// jquery function | |
$.fn.inputResetable = function(defaultValue) { | |
return this.each(function() { | |
new InputResetable(this, defaultValue); | |
}); | |
}; | |
// default use on this class | |
$('input.resetable').inputResetable(); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment