CSS Tricks: Create Custom Dropdown with Button
In this part of the series CSS Tricks, we will do custom dropdown with a button. The default bootstrap dropdown component works very well but in some rare cases we want after the selection of the dropdown for example if it is a link, not to go straight on the next page, but to have a Go
button, in this case, we need to make custom dropdown. For that purpose, we will use the select
HTML element and option
HTML element, also we will need the jQuery library. Let's see how the code should look in our example:
HTML code:
<div>
<select id="customDropdown" required>
<option value="" disabled selected hidden>Pick an option..</option>
<option value="value-one">Option One</option>
<option value="value-one">Option Two</option>
<option value="value-one">Option Three</option>
</select>
<a id="goBtn" class="btn">GO</a>
</div>
CSS code:
.dropdown{
text-align: center;
left: 0.8%;
top: 30%;
position: relative;
}
#customDropdown{
height: 50px;
width: 320px;
padding: 0 20px;
border-radius: 30px;
border: 1.5px solid #76b520;
color: #76b520;
font-size: 20px;
outline: none;
appearance: none;
-webkit-appearance: none;
-moz-appearance: none;
}
#goBtn{
height: 50px;
width: 50px;
padding: 17px 14px;
border-radius: 50%;
background-color: #ff9700;
color: #fff;
font-weight: bold;
font-size: 15px;
position: relative;
right: 54px;
bottom: 1.25px;
cursor: pointer;
}
JavaScript code:
$("#customDropdown").change(function (e) {
var selectedValue = $('#customDropdown').val();
$("#goBtn").click(function (e) {
$("#goBtn").attr("href", "/nextpage/");
});
});
And when we look up in the browser the result should look like this:
We are using <div>
as a root element, inside we have <select>
element and an <a>
element. In the <select>
element we have four <option>
element which the first one is just for the text placeholder inside our dropdown menu, and the other three are the possible options.
The <a>
element is a simple link, also we are getting selected value from the dropdown inside our JavaScript code. You may need to use different values depending on the size of the dropdown.
Tweet