Getting placeholder to disappear/appear and positioning the cursor in front
I'm a total beginner to JavaScript, jQuery, and everything else, so when I saw that HTML5 supports placeholder I was satisfied. That is, until I wanted to enhance its behavior. What I'm trying to do is take what I learned in this post (particularly开发者_开发技巧 the corresponding jsFiddle) but modifying it so that:
- When focusing on the input field, the cursor automatically goes to the beginning of the placeholder in a way that you don't see it move.
- The placeholder disappears when I start typing (not after an amount of time) in my input field (which it does but then reappears if I delete what I typed in my input field.
I've seen sleek implementations that do exactly what I'm looking to do (notably from the homepages of Tubmlr and Square, and the "Join" page of Foursquare) and am hoping to find out how to do it myself.
The code from the aforementioned jsFiddle that I want to modify/enhance:
$('.placeholder').each(function(){
$(this).data('placeholder', $(this).attr('data-title'));
$(this).val($(this).attr('data-title'));
});
$('.placeholder').live('keydown', function(){
if ($(this).val() == $(this).data('placeholder')) {
$(this).val('');
}
});
$('.placeholder').live('blur', function(){
if ($(this).val().trim() == '') {
$(this).val($(this).data('placeholder'));
}
});
Can anyone help explain this to me?
<style>
form div {
position:relative;
}
div label {
position:absolute;
top:0;
left:0;
color:#666;
}
div input {
background: transparent;
}
</style>
...
<script>
$(document).ready(function() {
$('input').keyup(function() {
if ($(this).val().length) {
$('label[for='+$(this).attr('name')+']').fadeOut();
} else {
$('label[for='+$(this).attr('name')+']').fadeIn();
}
});
});
</script>
...
<form>
<div>
<label for="name">Name</label>
<input id="name" name="name" />
</div>
</form>
http://jsfiddle.net/Pbn5K/4/
Edit - it appeared to me Tumblr was setting a background image with text rendered in it (notice the text isn't selectable) on focus. So just put a background image in the input while it has focus, then remove it on blur. This isn't how they do it as js1568 points out. That said, this is how I've implemented elsewhere. The label method referred too looks easier and more straightforward.
$(your input selector here).focus(function(){
$(this).css('background-image', 'url(background image with text in it.png)');
});
$(your input selector here).blur(function(){
$(this).css('background-image', 'url(background image in different color with text in it.png');
});
When the user starts typing, they change the background image, so you'll need to check the value of the input while they're typing to see if it's empty - if it isn't, remove the background image:
$(your input selector here).keypress(function(){
if ($(this).val() != "") {
$(this).css('background-image', '');
}
});
精彩评论