Friday, December 14, 2012

How to create stylish SelectBox with HTML and Javascript

We can create good-looking selectbox in various ways ... one of them is described below.

1. We'll use a DIVwith a background image which will represent the finally good looking selectBox
2. We'll put a SelectBox inside the DIV and make the SelectBox completely invisible by setting its opacity to zero and Z-index to 100
3. We'll have a SPAN [Sibling to SelectBox] inside the DIV, which will show the final text after we select an Item from the SelectBox

Process ::

1. We are shown the SPAN with a default text
2. When we click on the DIV, the SelectBox receives the click because of having the highest z-index
3. One JS function runs when click event is captured on the SelectBox and that function extracts the textContent from the SelectBox and puts it in the SPAN


 -----OUTER DIV ----------------------------------------
|  -- SelectBox [Invisible but stays at the top] -----  |
| |                                                   | |                            
| |___________________________________________________| |
|                                                       |
|  -- SPAN [Holds the text] --------------------------  |
| |                                                   | |                            
| |___________________________________________________| |
|                                                       |
|-------------------------------------------------------|


Check the code below and see the effect

<script type='text/javascript'>
  function run(elem)
  {
    var p = elem.nextElementSibling;
    if( elem.value!='')
     p.innerHTML = elem.options[elem.selectedIndex].textContent;
    else
     p.innerHTML = "Select Order";   
  }
 </script>

<div>
  <!-- OUTER DIV STARTS -->
  <div class="select1" style='height:25px;display:block; background: url("bg_select.png") no-repeat scroll 1px 2px transparent;'>
        <!-- SELECTBOX Starts -->
    <select title="Select Order" class="select2" id="select" onchange="run(this)" name="data[productsortoforder]" style="z-index: 10; opacity: 0;">
        <option value="">Select Order</option>
        <option value="name-asc">Name: Ascending</option>
        <option value="name-desc">Name: Descending</option>
        <option value="price-lowtohigh">Price: Low To High</option>
        <option value="price-hightolow">Price: High To Low</option>
    </select>
        <!-- SPAN STARTS -->
    <span style='border:0px solid red; margin-left:-137px;margin-top:3px; position:absolute; font-family:helvetica; font-size:12px'>Select Order</span>      
  </div>
</div>


Check the final getUp as displayed below ::



Save the picture below as bg_select.png and run the above code to check the effect.


No comments: