Reputation: 789
I have created a placeholder around an <input>
field:
HTML:
<div style="position: relative;font-size: 20px;">
<input type="text" name="username" id="lgip" style="width: 100%" class="lgip" value="<?php echo $username ?>" onkeyup="perform(this.value,'plcun')"/>
<div class="placer" style="padding: 5px" onclick="$('#lgip').focus()" id="plcun">Enter UserName or Email Address</div>
</div>
JavaScript:
function perform(val,hid){
if(val=="") {
$("#"+hid).show();
} else{
$("#"+hid).hide();
}
}
CSS:
input.lgip{ padding: 5px;font-size: 20px;border: 1px solid #2B4EA2 }
div.placer{ position: absolute;z-index: 5;top: 0px;left: 0px;background: transparent;width: 100%;color: #cccccc;white-space: nowrap;padding: 2px;padding-left: 4px }
Currently this requires me to add an outher <div>
around the <input>
and another <div>
below it.
I want to extend jQuery so it can make a placeholder for any input:text
and textarea
, so that when I use something like $("#lgip").makePlacer("Enter Username Or Email");
it will make a placeholder like the one I created.
Upvotes: 0
Views: 209
Reputation: 4020
Writing jQuery plugins is actually quite easy. Basically you just add your plugin function to the jQuery.fn
object. In the plugin you can create the desired HTML elements and add them to the DOM.
(function($){
$.fn.makePlacer = function(text){
this.each(function(){
var e = $(this);
if (e.is("input[type='text'], textarea")) {
var wrapper = $("<div/>").css({position: "relative", fontSize: 20});
var placer = $("<div/>").html(text != undefined ? text : "").css({padding: 5}).addClass("placer").click(function(){
e.focus();
});
e.wrap(wrapper);
e.after(placer);
e.keyup(function(){
e.val().length ? e.next().hide() : e.next().show();
});
}
});
};
})(jQuery);
$("#lgip").makePlacer("Enter Username Or Email");
JSFiddle: http://jsfiddle.net/QQdfQ/1/
Upvotes: 1