Tuesday, October 8, 2013

How to define the CSS class that should be used during an onMouseOver or onMouseOut event for a web control

In case you would ever like to leverage an existing CSS class for your web control whenever an mouse event is triggered (i.e. onMouseOver or onMouseOut), here is a quick example of how to do that:

<input type="button" class="ui-state-default ui-widget-content" onMouseOver="this.className='ui-state-default ui-widget-content ui-state-hover'" onMouseOut="this.className='ui-state-default ui-widget-content'" value="Submit" id="btnSubmit" onClick="SubmitForm();" />

NOTE: In the above example, I'm leveraging the CSS classes that are already defined for a jQuery UI Calendar control that exists on another part of the page.  By leveraging those CSS classes for my control, I can keep the look and feel of all controls on the page as consistent as possible.

Also, there may come a time when you need to assign the CSS classes a web control uses via Javascript code. In the following example, I'm using a Javascript function to specify the CSS classes that will be programmatically defined for the given control based on the isSelected value (i.e. whether or not the control has been selected):

function SetButtonStyle(controlId, isSelected) {
     if (isSelected) {
          document.getElementById(controlId).onmouseout = "this.className='ui-state-default ui-state-highlight ui-state-active'";
          document.getElementById(controlId).onmouseover = "this.className='ui-state-default ui-state-highlight ui-state-active'";
          document.getElementById(controlId).className = "ui-state-default ui-state-highlight ui-state-active";
      }
      else {
          document.getElementById(controlId).onmouseout = "this.className='ui-state-default ui-widget-content'";
          document.getElementById(controlId).onmouseover = "this.className='ui-state-default ui-widget-content ui-state-hover'";
          document.getElementById(controlId).className = "ui-state-default ui-widget-content";
      }
}