Search code examples
web-applicationsjsf-2java-ee-6

Highlighting commandbutton jsf 2.1 when pressed


I am using JSF 2.1 to code a web application. I would like to use 2 buttons to take me to two different views passing a param. But by default I have one button "pressed" and therefore it should be "depressed" in the view. How can I show this sort of a bahaviour? here is the small piece of code where I have two buttons:

                                    <h:outputLabel value="Color:" />
                                    <!--blue button is highlighted as pressed by default -->
                                    <h:commandButton  value ="blue" action="#{bean.update}" >
                                        <f:setPropertyActionListener target="#{bean.color}" value="blue" />
                                    </h:commandButton>

                                    <!--green button is highlighted as pressed when clicked -->
                                    <h:commandButton value ="green" action="#{bean.update}" >
                                            <f:setPropertyActionListener target="#{bean.color}" value="de" />
                                    </h:commandButton>

Solution

  • You can add any kind of style to your h:commandButton as you would do to a normal button. For example to have a disabled button feel you can just set the opacity of your first button by default.

    <h:commandButton  value ="blue" action="#{bean.update}" 
                      style="opacity: 0.65" >
                     <f:setPropertyActionListener target="#{bean.color}" value="blue" />
    </h:commandButton>
    

    Or just add css class to your button using styleClass attribute

    <h:commandButton  value ="blue" action="#{bean.update}" 
                      styleClass="pressedButtonStyle" >
                     <f:setPropertyActionListener target="#{bean.color}" value="blue" />
    </h:commandButton>
    

    To change the class of your second button you can use onClick function to add a new css style to the button:

    <h:commandButton value ="green" action="#{bean.update}" onClick="$(this).addClass("pressedButtonStyle")" >
        <f:setPropertyActionListener target="#{bean.color}" value="de" />
    </h:commandButton>
    

    If you want to keep the state of buttons after returning to page you can apply these classes according to conditions such as this:

    <h:commandButton  value ="blue" action="#{bean.update}" style="opacity : #{bean.color eq 'blue' ? 0.65 : 1}">
          <f:setPropertyActionListener target="#{bean.color}" value="blue" />
    </h:commandButton>
    
    <!--green button is highlighted as pressed when clicked -->
    <h:commandButton value ="green" action="#{bean.update}"  style="opacity : #{bean.color eq 'de' ? 0.65 : 1}" >
          <f:setPropertyActionListener target="#{bean.color}" value="de" />
    </h:commandButton>