Create a Custom Select Box with jQuery

Create a Custom Select Box with jQuery

In this tutorial I will be teaching you how to transform boring select boxes into well styled form elements that are perfect for custom web applications. Using custom form elements such as select boxes can give your website a unique feel and make it stand out from the crowd.

By the end of the tutorial you will have a fully functioning custom select box.

Create a Custom Select Box with jQuery
[tut demo=”http://www.onextrapixel.com/examples/jquery-custom-selectbox/” download=”http://www.onextrapixel.com/examples/jquery-custom-selectbox/jquery-custom-selectbox.zip”]

The HTML Code

Firstly lets go over the HTML required for a normal select box. As you probably know a select box is comprised of a main container inside which contains each select option.

<select>
	<option></option>
	<option></option>
	<option></option>
</select>

Now in order to create our custom select box we need to duplicate this HTML structure using div and span elements. Lets go build up the structure from the outside in.

In the normal select box the outer wrapper is a select tag this can be easily replicated by using a couple of div and span tags as below:

<div class='selectBox'>
	<span class='selected'></span>
	<span class='selectArrow'>&#9660</span>
</div>

As you can see we now have the first blocks of our select box. This is made up of an outer div containing two span elements. One is to display the current option text and the other is to mimic the drop down arrow button you commonly see. Each tag for select will be given it’s own CSS class in order for jQuery to identify it and for us to give it the correct functionality later on in this tutorial. You will also see that the selectArrow span contains some text which you should recognise as a unicode value. This is code for a downward triangle shape &#9660 which will replace the drop down arrow seen on standard select boxes.

Next is the select options, these are to be placed after the selectArrow span tag like so:

<div class='selectBox'>
	<span class='selected'></span>
	<span class='selectArrow'>&#9660</span>
	<div class="selectOptions" >
		<span class="selectOption" value="Option 1">Option 1</span>
		<span class="selectOption" value="Option 2">Option 2</span>
		<span class="selectOption" value="Option 3">Option 3</span>
	</div>
</div>

Each option is represented as a span tag which holds the value attribute and inner text like a normal option tag. These are contained in a div with class ‘selectOptions’.

Here is a shot of what we have so far:

HTML Arrow

So that’s the HTML part of the select box covered but as you know this means nothing without the accompanying CSS to give its unique look which is what we’re going to add next.

The CSS Code

Now we define the style of our select via CSS. First here is a list of what CSS selectors we will be using:

  • span.selectOption – each option item
  • span.selectOption:hover (for mouse rollover effects)
  • span.selectArrow – drop down arrow button
  • span.selected – stores the selected option text
  • div.selectBox – main select box container
  • div.selectOptions – select options container

Firstly lets tackle the top parts of the select box which are div.selectBox, span.selectArrow and span.selected. Here is the code:

div.selectBox {
	position:relative;
	display:inline-block;
	cursor:default;
	text-align:left;
	line-height:30px;
	clear:both;
	color:#888;
}
span.selected {
	width:167px;
	text-indent:20px;
	border:1px solid #ccc;
	border-right:none;
	border-top-left-radius:5px;
	border-bottom-left-radius:5px;
	background:#f6f6f6;
	overflow:hidden;
}
span.selectArrow {
	width:30px;
	border:1px solid #60abf8;
	border-top-right-radius:5px;
	border-bottom-right-radius:5px;
	text-align:center;
	font-size:20px;
	-webkit-user-select: none;
	-khtml-user-select: none;
	-moz-user-select: none;
	-o-user-select: none;
	user-select: none;
	background:#4096ee;
}

span.selectArrow,span.selected {
	position:relative;
	float:left;
	height:30px;
	z-index:1;
}

Now you should be familiar with CSS anyway so I won’t go into too much detail about this code but here are a few of the major points.

  • span.selectArrow and span.selected are set to float left so that they are placed inline with each other. They are also given the same height. line-height:30px makes the options and arrow align vertically in their respected containers.
  • span.selectArrow is given a curved border on the right and selected is given a curved border on the left so that together the select box edges are all curved.
  • clear:both is placed into div.selectBox to counter the effects of using float in span.selectArrow and span.selected.
  • A font size of 20px is set in the selectArrow to enlarge the unicode triangle as it’s a bit small in relation to the select box size.

NOTE: You may need to change the z-index:1 value in the span.selectArrow,span.selected selector in order for it to comply with your web pages.

Now that we’re half way through the CSS, this is what the select box looks like so far.

CSS Part 1

Its starting to resemble a select box now let finish off the CSS code by adding the following:

div.selectOptions {
	position:absolute;
	top:28px;
	left:0;
	width:198px;
	border:1px solid #ccc;
	border-bottom-right-radius:5px;
	border-bottom-left-radius:5px;
	overflow:hidden;
	background:#f6f6f6;
	padding-top:2px;
	display:none;
}
	
span.selectOption {
	display:block;
	width:80%;
	line-height:20px;
	padding:5px 10%;
}

span.selectOption:hover {
	color:#f6f6f6;
	background:#4096ee;			
}			

Again I’ll just go over the major points of this code:

  • The selectOptions is given a relative position of top:-4px and in combination with the z-index:1 of the span.selected and span.selectArrow, it’s slightly underlapped to make it look more like a drop down menu.
  • The bottom edges of the div.selectOptions are curved.
  • The width of div.selectOptions is set to the width of the span.selected + span.selectArrow minus 2px to take into account the div.selectOptions border.
  • The div.selectOptions has a top padding to counteract the relative positioning so each item looks the same height.
    Ok, that’s all the CSS finished, lets see what the select box looks like now (I have commented out the display:none in the div.selectOptions so you can see it).

CSS Part 2

The jQuery Code

Now that we have both the CSS and HTML in place we can begin writing the jQuery to give this custom select box its functionality.
First we’ll define a JavaScript function which inside will house our jQuery code. This function can then be run when you want to enable the select boxes which will most likely be when the page has loaded using the $(document).ready function of jQuery. Here is a skeleton of the code:

$(document).ready(function() {
	enableSelectBoxes();
});

function enableSelectBoxes(){
	$('div.selectBox').each(function(){
		//do something
	});
}

As you can see by using jQuery we are going to iterate through each select box container by using the .each() function. To make it easier, we’ll break down the function into different sections and gradually create a working custom select box.

Firstly we want the text of the first option to appear in our span.selected and we also want the value of the first option to be set to our div.selectBox so that other functions can see what the select box has got selected. This is done with 2 lines of code which are:

$(this).children('span.selected').html($(this).children('div.selectOptions').children('span.selectOption:first').html());
$(this).attr('value',$(this).children('div.selectOptions').children('span.selectOption:first').attr('value'));

This piece of code uses jQuery’s traversal functions in order to obtain and set the text and value in their respected tags.
Next we need to set up an event so that when either the span.selected or span.selectArrow is clicked, the div.selectOptions is shown or hidden depending on its current state:

$(this).children('span.selected,span.selectArrow').click(function(){
	if($(this).parent().children('div.selectOptions').css('display') == 'none'){
		$(this).parent().children('div.selectOptions').css('display','block');
	}
	else
	{
		$(this).parent().children('div.selectOptions').css('display','none');
	}
});

This piece of code again uses jQuery traversal functions and sets the CSS property – display to either block or none on the div.selectOptions.

A last piece of code is required to control when one of the options in the select box is clicked. When an option is clicked its text and value need to be assigned to the span.selected and div.selectBox respectively.

$(this).find('span.selectOption').click(function(){
	$(this).parent().css('display','none');
	$(this).closest('div.selectBox').attr('value',$(this).attr('value'));
	$(this).parent().siblings('span.selected').html($(this).html());
});

Putting these 3 pieces of code together gives us the full code for the function and with that, we have completed the custom select box in its entirety.

Advanced Enhancements

Following the steps above will give you a fully working custom select box, however there are a number of extra features you may wish add to your select box depending on how it will be used. Unfortunately these extra features are beyond the scope of this tutorial but here are some ideas that you could consider adding:

  • Add gradient backgrounds for the arrow button or select options.
  • Animate the drop down selection list.
  • Automatic transformation of normal select box to custom.
  • Retract the select options when there is a click outside the select box.

jQuery

[tut demo=”http://www.onextrapixel.com/examples/jquery-custom-selectbox/” download=”http://www.onextrapixel.com/examples/jquery-custom-selectbox/jquery-custom-selectbox.zip”]

To Conclude

Hopefully by now you should have your very own custom select box which looks something like the above so congrats to you! Please feel free to comment and drop me a link if you decide to include a custom select box, as I would love to see it in action.

Peter is a self taught (mostly) programmer with a keen interest in web based applications. He is always keen to learn anything IT related. He likes to create useful and easy to use tools for all to enjoy. If he has a design in his head he will make it come to life.

Comments

  1. / Reply

    Simple implementation but you missed one potentional use case and your selectbox fails in usability. Users are able select an option by pressing a char key on their keyboard and your custom design does not reflect this possibility. Imagine that you will use it for a long list and scrolling by mouse wheel or by scrollbar is ineffective.

  2. / Reply

    This is the worst tutorial I’ve ever seen!
    This is not even a selectbox, it’s just hiding and showing some div’s.
    A selectbox starts with a tag, not with a tag.

  3. / Reply

    Also, I forgot to say, it only works on one div.
    If I want to use this on more occasions, I have to copy all the html code every time in the exact same way.
    What if I post this in a form? There is no POST value, so how do I know what I selected?

    1. / Reply

      Here is a revision of the jQuery code. This will iterate over all normal select boxes defined in the web page and ‘transform’ them into custom select boxes. It will in fact simply hide the regular select boxes and update its value when the custom select box value is changed so if the select box is placed in a form its value can still be obtained when submitted:

      function enableSelectBoxes(){

      $(‘select’).each(function(){
      var origSelect = $(this);
      var select = $(”).addClass(‘selectBox’);
      select.append($(”).addClass(‘selected’),$(‘&#9660’).addClass(‘selectArrow’),$(”).addClass(‘selectOptions’));
      var options = select.children(‘div.selectOptions’);
      origSelect.children(‘option’).each(function(){
      var option = $(”).addClass(‘selectOption’);
      option.html($(this).html());
      option.attr(‘value’,$(this).attr(‘value’));
      options.append(option);
      });
      select.append(options);
      origSelect.after(select);
      origSelect.css(‘display’,’none’);

      select.children(‘span.selected’).html(select.children(‘div.selectOptions’).children(‘span.selectOption:first’).html());
      select.attr(‘value’,select.children(‘div.selectOptions’).children(‘span.selectOption:first’).attr(‘value’));
      origSelect.attr(‘value’,select.children(‘div.selectOptions’).children(‘span.selectOption:first’).attr(‘value’));

      select.children(‘span.selected,span.selectArrow’).click(function(){
      var selectOptions = $(this).parent().children(‘div.selectOptions’);
      if(selectOptions.css(‘display’) == ‘none’){
      selectOptions.css(‘display’,’block’);
      }
      else
      {
      selectOptions.css(‘display’,’none’);
      }
      });

      select.find(‘span.selectOption’).click(function(){
      $(this).parent().siblings(‘span.selected’).html($(this).html());
      $(this).parent().css(‘display’,’none’);
      $(this).closest(‘div.selectBox’).attr(‘value’,$(this).attr(‘value’));
      origSelect.attr(‘value’,$(this).attr(‘value’));
      });
      });
      }

    • Aldrin,
    • July 28, 2012
    / Reply

    This is just okay if it is not going to communicate with the server, say just for displaying purposes in the client-side. But if you want to submit it, you can add a custom data attribute to the span elements (take note that span element has no value attribute) and then submit it via jQuery AJAX methods, but that is a lot of work to do.

    I can say that this is practically not advisable since we achieved the custom styling but lost its functionality as a select element.

    By the way, check out these links:
    http://cssglobe.com/post/8802/custom-styling-of-the-select-elements
    http://jquery-ui.googlecode.com/svn/branches/labs/selectmenu/index.html

    Thank you.

      • McKay,
      • September 17, 2012
      / Reply

      This is a good start for a select box replacement. True you loose the functionality of the submit and the better implementation would be to mask the select element, but if you are still submitting your forms using the classic submits than you should update your development methods to use the ajax approach. It really isn’t that difficult, just use a little jquery (the long way)

      $.ajax({
      url: ‘yourPage.php’,
      type: ‘POST’,
      data: { selectValue: $(‘#yourSelectBox’).attr(‘value’) }
      }).done(function(res){
      //do something
      });

      Why it would be nice to extend the ‘select’ element:

      $.post(“yourPage.php”, $(“#testform”).serialize());

      this would submit the whole form for you.

      thats it. You now have the ability to do perform your save asynchronously and not have to reload any pages, plus you can use a development model that is far more robust and easier to test because things are seperated. Ajax is what is bringing about the performance and usability of web 3.0.

    • Marvin,
    • August 16, 2012
    / Reply

    Good tutorial, but it breaks for me in IE7. I want to align the select boxes next to each other, works in all browsers but they are stacked one on top of the other in IE7. Still trying to figure out the CSS change to make

      • Marvin,
      • August 16, 2012
      / Reply

      Sorted it out. I added another div outside each select. The div is floated left and has a width. Thanks for the great tutorial :)

    • Pete,
    • October 5, 2012
    / Reply

    Thanks for the tutorial. I have everything working on the site except the click event. When I click a select from the dropdown, how to I forward the user to another html page? I’m a noob so thanks for the help.

    The tutorial was very easy to follow and greatly appreciated!

    • Pete,
    • October 6, 2012
    / Reply

    Duh…sorry for the silly question. My brain has melted from working too late.
    Got it working after a decent night’s sleep.

    Thanks again for the nice tutorial.

    • George,
    • November 20, 2012
    / Reply

    Ok i have a problem when i put 2-3-4 of theese select when i click first and don’t select anything and click another one the first select stay still open can anyone help me?

  4. / Reply

    create one div or span assign the id name key at this same time create anyone popup give id name key_con,
    when you click key pop up will show.
    once again you click the key popup will hide .

    look this code:

    $(‘#key’).live(‘click’, function(){
    if(!key){
    $(‘#key_con’).show();
    key = true;
    }
    else if(key){
    $(‘#key_con’).hide();
    key = false;
    }
    });

    • Roee Yossef,
    • January 1, 2013
    / Reply

    Work Great ! Thanks.

    • Glow74ind,
    • January 17, 2013
    / Reply

    I tried using the code, but the dropdown list does not hide if the user decides not to select any instead.
    Secnario: what if the user clicks on the list to check the options but then decides not to select any option. The list does not lose focus.
    Can you help me with where I am going wrong.

    • ØŠâmã ËLŽèrÖ,
    • June 12, 2013
    / Reply

    Work Great After Some CSS Edits Thanks

  5. / Reply

    thanks a lot!

Leave a Reply

Your email address will not be published. Required fields are marked *

Deals

Iconfinder Coupon Code and Review

Iconfinder offers over 1.5 million beautiful icons for creative professionals to use in websites, apps, and printed publications. Whatever your project, you’re sure to find an icon or icon…

WP Engine Coupon

Considered by many to be the best managed hosting for WordPress out there, WP Engine offers superior technology and customer support in order to keep your WordPress sites secure…

InMotion Hosting Coupon Code

InMotion Hosting has been a top rated CNET hosting company for over 14 years so you know you’ll be getting good service and won’t be risking your hosting company…

SiteGround Coupon: 60% OFF

SiteGround offers a number of hosting solutions and services for including shared hosting, cloud hosting, dedicated servers, reseller hosting, enterprise hosting, and WordPress and Joomla specific hosting.

d
c