jQuery: Twitter with HTML5 contenteditable

With the introduction of the HTML5 contenteditable attribute, the good old days of the textarea-driven pages are over. Now by setting this attribute to true, any element of your page becomes editable, that is, its contents can be actually determined by the user's action. In this post, we're going to make a field trip by building up a content editable area for writing a Twitter tweet.

Let's start with setting up our editable area:

<div id="content" contenteditable="true"></div>

Now let's add a couple of CSS styles to make this area stand out of the rest of the page:

#content {
 margin: 1em 0;
 height: 150px;
 border: 1px solid #666;
 outline-style: none;
 overflow: auto;
}

#content:focus {
 background: #ffc;
}

When this area gets focus, its background color changes to a pale yellow thanks to the :focus CSS pseudo-class. Now we want to create a counter that basically keeps tracks of the number of characters typed in the editable area. Since we deal with Twitter, 140 characters are the limit. When 140 characters have been typed, the editable area should be no longer editable so that a user cannot insert more characters. Let's see how:

$(document).ready(function() {
  
  var counter = 0;
  $('#content').keypress(function() {
  
     
    
      counter += 1;
      $('#content').next().html(counter);
      
      
      
      if(counter == 140) {
      
        $(this).unbind('keypress').removeAttr('contenteditable');
      
      
      }
    
    
      
  
  });

});

When there are 140 characters in the editable area, the contenteditable attribute is removed from the element and the keypress event is unbound from the editable area. Note that this tracking system has only a demonstrative purpose: for more consistent results, you should use the keyCode property of the event object to check exactly what kind of characters have been typed. You can see the demo below.

Demo

Live demo

Leave a Reply

Note: Only a member of this blog may post a comment.