Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
27
rated 0 times [  29] [ 2]  / answers: 1 / hits: 47675  / 12 Years ago, wed, november 7, 2012, 12:00:00

I am trying to show a description when hovering over an option in a select list, however, I am having trouble getting the code to recognize when hovering.


Relevant code:


Select chunk of form:


<select name="optionList" id="optionList" onclick="rankFeatures(false)" size="5"></select>
<select name="ranks" id="ranks" size="5"></select>

Manipulating selects (arrays defined earlier):


function rankFeatures(create) {

var $optionList = $("#optionList");
var $ranks = $("#ranks");

if(create == true) {
for(i=0; i<5; i++){
$optionList.append(features[i]);
};
}
else {
var index = $optionList.val();
$('#optionList option:selected').remove();
$ranks.append(features[index]);
};

}


This all works. It all falls apart when I try to deal with hovering over options:


$(document).ready( 

function (event) {
$('select').hover(function(e) {
var $target = $(e.target);
if($target.is('option')) {
alert('yeah!');
};
})
})

I found that code while searching through Stack Exchange, yet I am having no luck getting it to work. The alert occurs when I click on an option. If I don't move the mouse and close the alert by hitting enter, it goes away. If I close out with the mouse a second alert window pops up. Just moving the mouse around the select occasionally results in an alert box popping up.


I have tried targeting the options directly, but have had little success with that. How do I get the alert to pop up if I hover over an option?


More From » jquery

 Answers
107

You can use the mouseenter event.



And you do not have to use all this code to check if the element is an option.



Just use the .on() syntax to delegate to the select element.



$(document).ready(function(event) {
$('select').on('mouseenter','option',function(e) {
alert('yeah');
// this refers to the option so you can do this.value if you need..
});
});


Demo at http://jsfiddle.net/AjfE8/


[#82141] Tuesday, November 6, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kristineterrak

Total Points: 74
Total Questions: 109
Total Answers: 115

Location: Anguilla
Member since Sun, Jan 29, 2023
1 Year ago
;