Tuesday, January 15, 2013

How an editable div is made

In my previous post I had shown how you can make a div to receive a focus event. Today I'll show how to make an editable div.

First you can't make a div editable. There's no such thing as an editable div. But a textarea works perfectly for editing. So the idea is to use a textarea for editing and a div for showing text.

Here follows our html code:

    <div id="output">text text text input</div>
    <textarea id="input" style="display: none;">text text text output</textarea>
As you can see we have a div and a textarea. We have assigned id attributes for both. The textarea is hidden by using inline style (display: none;) so that only the div is visible at the start.

The basic idea is to hide the textarea and to show the div then we viewing a text. Then a user clicks on a text we will hide the div and in its place textarea will be shown. We will use jquery library and focus and blur events.

The focus event is sent to an element when it gains focus. This event is implicitly applicable to a limited set of elements, such as form elements (<input>, <select>, etc.) and links (<a href>). In recent browser versions, the event can be extended to include all element types by explicitly setting the element's tabindex property. An element can gain focus via keyboard commands, such as the Tab key, or by mouse clicks on the element.

- JQuery docs

The blur event is sent to an element when it loses focus. Originally, this event was only applicable to form elements, such as <input>. In recent browsers, the domain of the event has been extended to include all element types. An element can lose focus via keyboard commands, such as the Tab key, or by mouse clicks elsewhere on the page.

- JQuery docs

so here follows the javascript code:

<script type="text/javascript">
  $(document).ready(function () {
    $('#output').focus(function() {
      $(this).hide();
      $('#input').height($(this).height())
          .width($(this).width())
          .show()
          .focus();
    });

    $('#input').blur(function() {
      $(this).hide();
      $('#output').html($(this).val()).show();
    });
  });
</script>
So first we find the div element by its id and subscribe it to focus event. In event handler we hide div ($(this).hide();) find textarea by its id and show it. Next subscribe textarea to blur event. In Blur handler we copy textarea text into div then hide textarea and show div again.

That is all, happy coding!