From cd7f8fda7afe12830f993dbe31193657c3d7f288 Mon Sep 17 00:00:00 2001 From: ympbyc Date: Wed, 26 Jun 2013 18:56:35 +0900 Subject: [PATCH] Preserve the position of the caret while editing a textarea or input[type=text]. --- src/webfui/plugin/form_values.cljs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/webfui/plugin/form_values.cljs b/src/webfui/plugin/form_values.cljs index e2fe523..80e5a5a 100644 --- a/src/webfui/plugin/form_values.cljs +++ b/src/webfui/plugin/form_values.cljs @@ -2,17 +2,22 @@ (:use [webfui.plugin.core :only [Plugin]] [webfui.dom-manipulation :only [select-path-html parsed-html unparse-html path-dom resolve-target]])) +(def caret (atom {})) ;;I know this is ugly but I wanted to do this inside a plugin + (defn input [dom-watchers parsed-html event] (let [target (.-target event) [tagname attributes :as element] (resolve-target @parsed-html target) event (@dom-watchers (keyword (:watch attributes)))] (when (and event (contains? #{:input :textarea} tagname)) (let [value (.-value target) + selPos (.-selectionStart target) new-element (update-in element [1 :value] (fn [old] (set! (.-value target) old) value))] + (reset! caret {:target target + :position selPos}) (event element new-element))))) (deftype form-values [] @@ -20,6 +25,7 @@ (declare-events [this body dom-watchers parsed-html] (.addEventListener body "input" (partial input dom-watchers parsed-html))) (fix-dom [this] - nil)) - - + (let [{:keys [target position]} @caret] + (when (and target position) + (set! (.-selectionStart target) position) + (set! (.-selectionEnd target) position)))))