Frank
Frank

Reputation:

select loses focus when mouse is over options

I am trying to do a hover effect as follows:

<div>Some Text</div>

should be substituted by a <select> upon mouseover. as soon as the mouse leaves that select it should display either the value previously displayed or the new selected value.

Unfortunately the mouseleave is called when you open the dropdown to select some options and I cannot get it to work. Has anyone had this problem before and knows the solution?

<div id="text">Some Text</div>
<select id="selector" style="display: none">
<option value="1" selected="selected">Some Text</option>
<option value="2">Some More</option>
<option value="3">Some Other</option>
</select>

the jQuery:

$("#text").mouseover(function()
{
    $(this).hide();
    $("#selector").show();
});

$("#selector").mouseleave(function()
{
    $(this).hide();
    $("#text").show();
});

Can anyone let me know how I can make sure that the mouseleave isn't called when somebody is opening the select and hovers over the options?

BTW: It does work when the mousebutton is being pressed during the selection

Upvotes: 4

Views: 3351

Answers (3)

Russ Cam
Russ Cam

Reputation: 125538

Wrap it in a wrapper <div> and set the event handlers on that

Working Demo

jQuery

$("#wrapper").mouseover(function()
{
    $("#text").hide();
    $("#selector").show();
});

$("#wrapper").mouseleave(function()
{
    $("#selector").hide();
    $("#text").show();
});

$("#selector").change(function() {
    var value = $(this).val();
    $("#text").text($("option[value='"+value+"']", this).text());

});

HTML

<div id="wrapper">

    <div id="text">Some Text</div>
    <select id="selector" style="display: none">

        <option value="1" selected="selected">Some Text</option>
        <option value="2">Some More</option>
        <option value="3">Some Other</option>

    </select>

</div>

Upvotes: 0

Jagd
Jagd

Reputation: 7306

Have you tried using the hover() event?

$("#text").hover(
function() {
    $(this.hide();
    $("#selector").show();
},
function() {
    $(this).hide();
    $("#text").show();
});

Upvotes: 0

mck89
mck89

Reputation: 19271

I think that you should use the change and blur events to do this:

var hidesel=function()
{
    $(this).hide();
    $("#text").show();
}
$("#selector").change(hidesel).blur(hidesel);

in this way the select will be hidden when the user clicks on an option or clicks outside the select. I think it's also more practice.

Upvotes: 1

Related Questions