I have a select box which i create dynamically with javascript i like to add a tooltip on over when going over a mouse on the selected option so it just gives me the text value of the option.
This is how i create the selectbox ( simple )
var selectBoxDB = document.createElement("select");
selectBoxDB .classList.add("form-control");
selectBoxDB .id = "select_"+mydata["source_name"];
selectBoxDB .style.width = "300px";
td.appendChild(selectBoxDB );
for(var key in mydata.servers_list) {
if (dbEntry.servers_list.hasOwnProperty(key)) {
var option = new Option(key, key);
option.title = key;
selectBoxDB .appendChild(option);
}
}
how to combine here or attach a function that when the select box created
when mouse over the selected option it will popup tooltip?
You could add a global mouse enter/leave listener to the <select>
to display a tooltip with the current value.
const tooltip = document.querySelector('.tooltip');
const showTooltip = (e) => {
Object.assign(tooltip.style, {
top: `${e.clientY + 8}px`,
left: `${e.clientX + 8}px`
});
tooltip.innerHTML = JSON.stringify({
value: `${e.target.value}`,
text: `${e.target.selectedOptions[0].text}`
}, null, 2);
tooltip.classList.add('show');
e.target.setAttribute('title', e.target.selectedOptions[0].text);
};
const hideTooltip = (e) => {
tooltip.classList.remove('show');
};
const attachListeners = (observeable) => {
observeable.addEventListener('mouseenter', showTooltip);
observeable.addEventListener('mouseleave', hideTooltip);
}
document.querySelectorAll('.observeable').forEach(attachListeners);
.tooltip {
display: none;
position: absolute;
border: thin solid #000;
padding: 0.5em;
background: rgba(0, 0, 0, 0.66);
color: #FFF;
white-space: pre;
font-family: monospace;
}
.show {
display: block;
}
<div class="tooltip">Hello World</div>
<select class="observeable">
<option value="apple">One</option>
<option value="banana">Two</option>
<option value="carrot">Three</option>
<option value="date">Four</option>
<option value="eggplant">Five</option>
</select>