FocusManager proposition
blabno Apr 22, 2011 7:01 AMHello,
I haven't found any component in Richfaces that would put focus on some element on page load.
Here is my proposition. Let's make rich:focus tag with "priority" attribute. Default priority would be position of input in form. This parameter will be usefull if we want to focus on first invalid element in form. Tag with lowest priority value will be focused.
if (!window.Richfaces) window.Richfaces = {}; Richfaces.FocusManager = (function(){ var m_focus; var m_priority = 999999; var eventAttached = false; var attachEvent = function() { if(!eventAttached) { document.observe('dom:loaded',function(){ var element = $(m_focus); element.focus(); element.select(element); }); } eventAttached = true; }; return { getFocus : function() { return m_focus; }, setFocus : function(id,priority) { if(priority == null) { priority = 99999; } if(m_focus == null || priority < m_priority) { m_focus = id; m_priority = priority == null ? 0 : priority; attachEvent(); } }, clearFocus : function() { m_focus = null; m_priority = 999999; } }; })();
XHTML source should look like this :
<h:form> <h:inputText value="#{somevalue}"> <rich:focus/> </h:inputText> </h:form>
Which would give priority = 1 and should produce following javascript :
Richfaces.FocusManager.setFocus("f:b",9999);
Other example:
<h:form> <h:inputText value="#{somevalue}"> <rich:focus priority="3"/> </h:inputText> </h:form>
Which would give priority = 3 and should produce following javascript :
Richfaces.FocusManager.setFocus("f:b",3);
Another example :
<h:form> <h:inputText value="#{somevalue}" id="a"> <rich:focus priority="9999" rendered="#{not invalid}/> <rich:focus rendered="#{invalid}"/> </h:inputText> <h:inputText value="#{somevalue2}" id="b"> <rich:focus rendered="#{invalid}"/> </h:inputText> </h:form>
That would cause following :
- if there is no validation error (i.e. initail request), focus is put on "a"
- if there is validation failure on "a" or on both, focus is placed on "a" due to lower priority (second focus child tag will be rendered with default priority calculated on position of "a" in enclosing form)
- if there is validation failure on "b" only, focus is placed on "b" because it's priority will be 2 (default) and "a" will have priority 9999 since first focus child tag will be rendered
I wonder if logic presented in javascript shouldn't be kept on server to avoid verbose javascript (suggested solution prints separate javascript for each rich:focus tag). I just don't know where if so.
Edited after several month:
Demo, download and subversion address are here.
Make sure to use default script and style loading strategies.