HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Styling <select> dropdowns with jQuery

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
dropdownswithjquerystylingselect

Problem

I am new to JavaScript, HTML and CSS, although not to programming.

I wanted to style 'select' dropdowns, so I wrote this:

What noob mistakes am I making? Is this a good or evil use of JS?

```

-->

body { font-family: sans-serif; }

.control { display: none; }
.dropdown > dl { margin: 4px; font-family: sans-serif; }
.dropdown > dl > dt { display:inline-block; width: auto; }
.dropdown .value { display: none; }
.dropdown > dl > dd { position: absolute; left: 0; top: 27px; display: none; }

.dropdown > dl { display:inline-block; width: auto; position: relative; cursor: pointer; }
.dropdown > dl > dt { border: 1px solid #ddd; background-color: #eee; color: black; padding: 3px 6px; font-weight: bold; }
.dropdown > dl > dd { border: 1px solid #ddd; background-color: white; margin:0;}
.dropdown > dl > dd > ul { padding:0; margin:0 }
.dropdown > dl > dd > ul > li { list-style: none; padding:5px 10px; padding-left: 28px; }
.dropdown > dl > dt:hover,
.dropdown > dl > dd > ul > li:hover { background-color: #333; color: white; }
.dropdown > dl > dd > ul > li { display: none; }
.dropdown li.selected:before { font-family: 'FontAwesome'; content: '\f00c'; margin: 0 5px 0 -22px; font-weight: normal; }
.dropdown li.selected { font-weight: bold; }

-->

function Dropdown(name) {
this.name = name;
this.$root = $('#dropdown').clone().removeAttr('id').show();
this.$root.children('dl').css('z-index', Dropdown.zindex.next());
Controls.registerControl(this);

this.$selected = this.$root.find('dt');
this.$selectedContents = {
$text: this.$selected.children('span.text'),
$value: this.$selected.children('span.value') };
this.$popup = this.$root.find('dd');
this.$options = this.$popup.children('ul');
this.$option = this.$options.children('li');
this.$optionContents = {
$text: this.$option.children('span.text'),
$value: this.$option.children('span.value') };

Solution

Tip for your code:

  • Use $name for var names that represent a jQuery selection, nor for a member (it is the convention).



  • Since you use jQuery, consider writing a plugin extending jQuery.fn instead of prototyping

Context

StackExchange Code Review Q#37908, answer score: 2

Revisions (0)

No revisions yet.