Skip to content

Instantly share code, notes, and snippets.

@magalhini
Last active December 19, 2015 02:39
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 magalhini/5884694 to your computer and use it in GitHub Desktop.
Save magalhini/5884694 to your computer and use it in GitHub Desktop.
Tiny gist to mimic placeholder behaviour in old IEs. To do: remove partial jQuery dependency.
/* Add Event Shim */
var addEvent = (function () {
var filter = function(el, type, fn) {
for (var i = 0, len = el.length; i < len; i++) {
addEvent(el[i], type, fn);
}
};
if (document.addEventListener) {
return function (el, type, fn) {
if ( el && el.nodeName || el === window ) {
el.addEventListener(type, fn, false);
} else if (el && el.length) {
filter(el, type, fn);
}
};
}
return function (el, type, fn) {
if ( el && el.nodeName || el === window ) {
el.attachEvent('on' + type, function () { return fn.call(el, window.event); });
} else if ( el && el.length ) {
filter(el, type, fn);
}
};
})();
var fakePlaceholder = (function () {
var placehold = {
/* Set placeholder value */
setValue: function (input) {
// If placeholder is supported, do nothing.
var test = document.createElement('input');
if ('placeholder' in test) return false;
if (input && input.length) {
var current = "",
value = "";
for (var i = 0; i < input.length; i += 1) {
var box = input.eq(i);
current = box[0].value;
value = box.attr('placeholder');
if (!current) {
box[0].value = value;
}
placehold._addEvents(box);
}
}
},
/* Add click and blur events */
_addEvents: function (input) {
addEvent(input, 'click', function () {
if (this.value === $(this).attr('placeholder')) {
this.value = '';
}
});
addEvent(input, 'blur', function () {
if (this.value === '') {
this.value = $(this).attr('placeholder');
}
});
}
};
return {
setValue: placehold.setValue
};
}());
/* Usage */
var input = $('input');
fakePlaceholder.setValue(input);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment