The question is how to add some onhover action to an HTML option tag in a datalist element.
The immediate answer is that you can't. You can't even style the individual options (though some browsers let you a little this is not standardised), let alone instigate some action onhover.
There are some workarounds:
- Automatically replace all such elements
You can introduce some Javascript which scans through your document, finds e.g. droplist or select elements, sets them not to display, and adds alongside them 'standard' elements like divs which emulate them. You can see further discussion on this for example at How to style the option of an html "select" element?
Although this might be useful, for example if you do not have complete control of all the source code, it adds a layer of complexity which isn't necessary if you can implement the HTML yourself.
- If you control the HTML, implementing your own options drop down is not very complex and has the added advantage that you can style things the way you want them to match the rest of your site, not rely on the (inconsistent) styling of such lists across browsers.
Here's some code to get you started. Add CSS to the elements as you like:
<head>
<style>
.select {
background-color: white;
width: 300px;
height: auto;
font-size: 16px;
border-style: solid;
padding: 10px;
}
.options {
display: none;
}
.option {
width: 100%;
height: 40px;
background-color: white;
}
.hoverinfo {
display: none;
float: right;
background-color: #eeeeee;;
}
ul {
list-style: none;
}
</style>
</head>
<body onclick="document.getElementById('select').firstElementChild.style.display='none';">
<div id="select" class="select" onclick="event.preventDefault();event.stopPropagation();this. firstElementChild.style.display='block';">
Select from this list
<ul class="options">
<li class="option" onclick="userhaschosen(this);" onmouseenter="event.preventDefault();event.stopPropagation();this.firstElementChild.style.display='block';" onmouseout="event.preventDefault();event.stopPropagation();this.firstElementChild.style.display='none';">
Option 1
<div class="hoverinfo">info about this option</div>
</li>
<li class="option" <li class="option" onclick="userhaschosen(this);" onmouseenter="event.preventDefault();event.stopPropagation();this.firstElementChild.style.display='block';" onmouseout="event.preventDefault();event.stopPropagation();this.firstElementChild.style.display='none';">
Option 2
<div class="hoverinfo">info about this option</div>
</li>
</ul>
</div>
<script>
function userhaschosen(el) {
event.preventDefault();
event.stopPropagation();
el.parentElement.style.display='none';
alert("user has chosen option "+el.firstChild.textContent);//instead of this alert, do whatever it is you want to do when the user has clicked an option
}
</script>
</div>