Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current value from datalist onhover

I'm trying to get the current value of the hovered element of a datalist. So if I open the datalist with values in it and just move my mouse over them, I want the values to appear in the console.

This is my attempt:

<input list="browsers" id="browser">
<datalist id="browsers">
    <option value="Internet Explorer">
    <option value="Firefox">
    <option value="Chrome">
    <option value="Opera">
    <option value="Safari">
</datalist>

$("#browsers").on("mouseover", function() {
  console.log($(this).value());
});

And here is a fiddle: https://jsfiddle.net/sshcvr5q/

like image 612
Evgenij Reznik Avatar asked Mar 09 '16 14:03

Evgenij Reznik


1 Answers

I'm not sure this is going to be possible. Datalist options, whilst still visible in the main document DOM tree, get cloned and encapsulated as part of a Shadow DOM tree, and as aren't accessible from the parent document. It is these encapsulated Shadow DOM nodes that you're actually hovering over (certainly in Chrome anyway), and the original node in the main DOM tree does not get triggered with a mouseover or hover event when you hover over the Shadow DOM nodes.

If you use Chrome DevTools to inspect the DOM tree in your JSFiddle example, you can see the Shadow Root of the encapsulated DOM tree:

Shadow DOM for input

See this explanation from another Stack Overflow question for further information about why you can't listen for events on the Shadow DOM from the parent document.

like image 197
toomanyredirects Avatar answered Oct 16 '22 09:10

toomanyredirects