Reputation: 774
I made a select with javascript and filled its options with an array. Afterwards I wrote some jquery to try and change the backgroundColor of the option when I hover over it, but nothing seems to work. everytime I hover over the options they are still highlighted blue.
I'm new to javascript and jquery and this is an idea that I had of why this happens: could this be because there is a standard hover function in a select that will always override mine or am I really overlooking a mistake? Because I tested my code before on divs and the code worked like a charm here
My code:
//arraycommObjName is an array with 4 elements to fill my selection
//$('#commObjs') is my select
for (i=0; i < arraycommObjName.length; i++) {
$('#commObjs').append($('<option class="testoptions"></option>').attr("value", arrayCommObjID[i]).text(arraycommObjName[i]));
}
$(".testoptions").hover(function(e) {
$(this).css("background-color",e.type === "mouseenter"?"green":"red")
})
take note yes I know it's better to do this with css but it is asked to me to do it with only javascript and jquery.
Upvotes: 1
Views: 3159
Reputation: 24720
You can use select2 and add some CSS to override the default styles.
Below is an example with some horrific colors to prove you can override the default select2 white and blue colors.
$("#states").select2();
#states {
width: 300px;
}
.select2-results__option {
color: orange;
background-color: seashell;
}
.select2-results__option--highlighted {
color: white !important;
background-color: darkgreen !important;
}
.select2-container--default .select2-results__option[aria-selected=true] {
background-color: darkgray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<select id="states">
<option value="">Select...</option>
<option value="AZ">Arizona</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value="NV">Nevada</option>
<option value="OR">Oregon</option>
<option value="PA">Pennsylvania</option>
<option value="RI">Rhode Island</option>
<option value="SC">South Carolina</option>
<option value="VT">Vermont</option>
<option value="VA">Virginia</option>
<option value="WV">West Virginia</option>
</select>
Upvotes: 2