You know those edit in place plugins for jQuery? Well I couldn’t find any that met these two criteria:
- Work on elements not yet in the DOM
- 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!
One thought on “LiveEdit”