开发者

Recreating Stackoverflow's question text field behavior using jQuery

If you look at the "Ask question" form in stackoverflow, the question input field is automatically selected. When you click on it, the whole thing disappears, aka Togg开发者_如何学GoleVal

However, if you use the toggleVal plugin, it automatically erases the default value upon .select(), even if the select() was done programatically

How does Stackoverflow prevent that automatic erasing?


I looked at the source and found this:

<input id="title" name="title" type="text" maxlength="300" tabindex="100" class="ask-title-field edit-field-overlayed" value="">                        
<span class="edit-field-overlay">what's your programming question? be specific.</span>

Based on that here is my assumption (without looking at the code). I'm thinking they use the text in the span tag as the default value for the text input. I know this because I changed the text in the span (using firebug) and then refocused into the field, it displayed my edited text. Anyway, here's something I quickly wrote.

// set the default value based on the span text
$('input[name=foo]').val($('.foo-overlay').text());

// whenever there is focus or blur
$('input[name=foo]').bind('focus blur',function(){

  // get the default text from the span
  var defaultText = $('.foo-overlay').text();

  // if the input field has default text
  if(this.value == defaultText){
    this.value = '';
  }
  // if the input is blank, set it to the default text
  else if (!this.value.length){
   this.value = defaultText;
  };

});​

Here's a demo. I'm not saying this is exactly how they are doing it. It's speculation based on a brief look.


edit

Just reread your question and realized you might be after how to not initially delete the default value? Check out this similar demo: http://jsbin.com/oyani4/2/

And here's the updated code:

// set the default value based on the span text
$('input[name=foo]').val($('.foo-overlay').text());

// whenever there is focus or blur
$('input[name=foo]').bind('focus blur',function(){

  // if there is no length, reset to default text
  if (!this.value.length){
    this.value = $('.foo-overlay').text();
  };

});

$('input[name=foo]').keydown(function(){

  // if there is length and it's not our default text
  if (this.value.length && this.value == $('.foo-overlay').text()){
    this.value = '';
  };

});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜