I'm writing a dropdown menu with several options and their colors. I have successfully colored the background of each option; however, once selected that background color doesn't show.
Is there a way to change this behavior? Example of my HTML below:
<select>
<option style="background-color: green">Successful</option>
<option style="background-color: orange">Process Failure</option>
<option style="background-color: purple">Abandoned</option>
</select>
or also here: http://jsfiddle.net/H8HVm/1/.
To add background color in HTML, use the CSS background-color property. Set it to the color name or code you want and place it inside a style attribute. Then add this style attribute to an HTML element, like a table, heading, div, or span tag.
You can change the background color and color of selected text by styling ::selection . Styling this pseudo element is great for matching user-selected text to your sites color scheme.
Add or change the background colorGo to Design > Page Color. Choose the color you want under Theme Colors or Standard Colors. If you don't see the color you want, select More Colors, and then choose a color from the Colors box.
Press the Windows key , type Settings, and then press Enter . In the Settings window, select the Personalization option from the left navigation menu. On the right side of the window, click the Background option.
You can use jQuery to read the class
of the selected option
then set that class
as the class
of the <select>
. Here is the code, followed by a fiddle:
$("#color_me").change(function(){
var color = $("option:selected", this).attr("class");
$("#color_me").attr("class", color);
});
.green {
background-color: green;
}
.orange {
background-color: orange;
}
.pink {
background-color: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="color_me" class="">
<option class="green">successful</option>
<option class="orange">process failure</option>
<option class="pink">abandoned</option>
</select>
Here's the JSFiddle: http://jsfiddle.net/DrydenLong/3QUN6/
Per request, here is a breakdown of my code above:
$("#color_me").change(function(){
This line calls function when the element with the id
of "color_me" is changed. i.e. an option from the select list is chosen.
var color = $("option:selected", this).attr("class");
This defines the variable color
as whatever the class
of the current selected option
is. The this
variable is referring to the DOM element we referenced in the first line. Basically this
ensures that we are getting the class from the correct <select>
i.e. the <select>
we just clicked on.
$("#color_me").attr("class", color);
});
This line assigns the color
variable defined above as the class
of the element with the id
of #color_me
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With