I’m working on a custom dropdown that I made, just wondering if I could get some advice as how to shorten / simplify my jQuery code. I have two lists that do the same thing and I have the code duplicated, which i know is long winded and really not a good approach.
example: http://jsfiddle.net/dg7Lc/22/
HTML:
<div class="custom-select list-one">
<span>Select Option</span>
<ul>
<li>List Item 1</li>
<li>List Item 2</li>
<li>List Item 3</li>
<li>List Item 4</li>
<li>List Item 5</li>
<li>List Item 6</li>
<li>List Item 7</li>
<li>List Item 8</li>
<li>List Item 9</li>
<li>List Item 10</li>
<li>List Item 11</li>
<li>List Item 12</li>
</ul>
</div>
<div class="custom-select list-two">
<span>Select Option</span>
<ul>
<li>List Item 1</li>
<li>List Item 2</li>
<li>List Item 3</li>
<li>List Item 4</li>
<li>List Item 5</li>
<li>List Item 6</li>
<li>List Item 7</li>
<li>List Item 8</li>
<li>List Item 9</li>
<li>List Item 10</li>
<li>List Item 11</li>
<li>List Item 12</li>
</ul>
</div>
JavaScript:
//Function for .list-one
$(function() {
$('.custom-select.list-one').click(function() {
$('.custom-select.list-one ul').slideToggle('fast');
});
$('.custom-select.list-one ul li').click(function() {
$(this).addClass('selected');
$('.custom-select.list-one span')
.html($('.custom-select.list-one ul li.selected').html());
$(this).removeClass('selected');
});
});
// Function for .list-two
$(function() {
$('.custom-select.list-two').click(function() {
$('.custom-select.list-two ul').slideToggle('fast');
});
$('.custom-select.list-two ul li').click(function() {
$(this).addClass('selected');
$('.custom-select.list-two span')
.html($('.custom-select.list-two ul li.selected').html());
$(this).removeClass('selected');
});
});
Any advice, thanks!
-Big D
Something like the following seems to work:
The idea is that you don’t need to know which of the selects was clicked on: whichever it is, you just find its child ul element using
$(this).find()and then toggle that. Similarly, when a li is clicked you just find the div element it belongs to with.closest()(you could also use.parent().parent()) and then from there find the associated span element.I also store a reference to the object returned by
$(this)rather than recreating it each time you need it.I noticed you were adding a “selected” class to the clicked li element only for use as a selector immediately afterwards, and then removing it again – you don’t need it at all since you already have a reference to the clicked element in
this.Note also that you don’t need two document.ready handlers: even for your code as you had it with the repetition you could’ve defined all of your click handlers within a single document.ready.
Also I wouldn’t use a class (like your “list-one” and “list-two”) to uniquely identify each list: that’s what the id attribute is for.
Demo: http://jsfiddle.net/dg7Lc/25/