• Follow me on:

Monday, November 12, 2012

Custom Select Box, using CSS and Jquery

It was July when I posted my last blog.  Was fullllllll busy with work and festivals.   Few days back I was preparing a HTML for a design provided by a client.  And the design was containing a select box with mastttt design.   So styling a select box is not possible with normal CSS.  You can style everything with the CSS except that right arrow.  So, google was the only hope and as usual I found the solution.  So, thought of sharing with you all.

HTML for the select box

<select class="select" title="Select one">
                <option></option>
                <option>Blue</option>
                <option>Red</option>
                <option>Green</option>
                <option>Yellow</option>
                <option>Brown</option>
</select>

CSS for the select box

/* setting the width and height of the SELECT element to match the replacing graphics */
select.select{
        position:relative;
        z-index:10;
        width:166px !important;
        height:26px !important;
        line-height:26px;
}

/* dynamically created SPAN, placed below the SELECT */
span.select{
    position:absolute;
    bottom:0;
    float:left;
    left:0;
    width:166px;
    height:26px;
    line-height:26px;
    text-indent:10px;
    background:url(selectBG.gif) no-repeat 0 0;
    cursor:default;
    z-index:1;
    }


you must make an image of size 166px X 26px.  The size of the select box and the background image which you are going to place as the select box should be same.  You can see the CSS for span.select{...}, I have used a background image selectBG.gif.

      Finally, the javascript you should use to make your customized select box. Use the following javascript and don't forget to include latest jquery file.

<script type="text/javascript">
    $(document).ready(function(){   

        if (!$.browser.opera) {   
            // select element styling
            $('select.select').each(function(){
               var title = $(this).attr('title');
                if( $('option:selected', this).val() != ''  ) title = $('option:selected',this).text();
                $(this)
                    .css({'z-index':10,'opacity':0,'-khtml-appearance':'none'})
                    .after('<span class="select">' + title + '</span>')
                    .change(function(){
                        val = $('option:selected',this).text();
                        $(this).next().text(val);
                        })
            });
        };       
    });
</script>


Following is the screen shot of the select box.  The black rounded select box in the screen shot is selectBG.gif which I used in the background of the select element.

I hope it is going to help you!! Byeeeeeeeeeeee and and dont forget to......

Share Your Solutions


No comments:

Post a Comment

All Rights Reserved Jaydharphics Click To Mail Me (+91 9564 5592 84)