LiveEdit

You know those edit in place plugins for jQuery? Well I couldn’t find any that met these two criteria:

  1. Work on elements not yet in the DOM
  2. Didn’t post anything to the server

Now the first requirement probably makes a lot of sense to you, but I bet you’re wondering about the second one. In these crazy mixed up times with rich HTML5 apps, I don’t want to post to the server often. Maybe I’m using local storage, or perhaps I just want to send a big heap of JSON now and again, but I definitely don’t want to post every time anyone changes the value of an editable field.

So after examining all the terrible options (classic first step when choosing jQuery plugins) I decided to throw my own terrible option into the mix.

(($) ->
  $.fn.liveEdit = () ->
    this.live 'dblclick', () ->
      $this = $(this)

      return if $this.is("input")

      textInput = $("",
        class: $this.attr("class")
        "data-origType": this.tagName
        id: if id = $this.attr("id") then id else null
        type: "text"
        value: $.trim($this.text())
      )

      $this.replaceWith textInput

      textInput.focus().select()

    this.live 'blur keydown', (event) ->
      if event.type == "keydown"
        return unless event.which == 13 || event.which == 9

      $this = $(this)

      return if $this.data("removed")
      return unless $this.is("input")

      $this.attr("data-removed", true)

      $this.replaceWith $("",
        class: $this.attr("class")
        id: if id = $this.attr("id") then id else null
        text: $this.val()
      )

    return this

)(jQuery)

There are two tricks here. The first is that this plugin is really a macro that makes two calls to live. The second is that the editable content keeps it’s same id and class when switched out to a text field, so as long as your selector is not based on the element type it will work. There’s plenty of room for improvements, but this is a super simple first step that meets my needs. Enjoy!

Author: Daniel X

Heretic priest of the Machine God. I enjoy crawling around in Jeff Bezo's spaceship, bringing technology to the people, and long walks outside of time and space.

One thought on “LiveEdit”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: