Question

What I'm attempting:

1-On hover of Div1, Div2 appears.
2-Div 2 has a text field.
3-When text field has focus, Div2 remains open even if hover is off Div1/Div2.
4-Clicking anything but Div2 hides Div2

http://jsfiddle.net/7FGK8/

<div id="one"></div>
<div id="two">
  <input type="text" id="text">
</div>

   $(document).ready(function() {
    if(!$('#text').is(":focus")) {
    $('#one, #two').hover(function() {
      $('#two').toggleClass('k k_b');
    });
  };
});

The div2 doesn't stay open onfocus, and I don't think I'm going about this the right way.
To me the code is saying:
"If #text doesn't have focus do this. If #text has focus don't do this."

The div2 hides off hover. Then once it has focus the only way to hide it would be clicking off. I'm not sure how event delegation would come into play here either. Anybody have any suggestions? I was thinking of using onblur to hide (or remove the new class).

Was it helpful?

Solution

First of all, you should hide the elements with opacity: 0 or display: none, this also allows you to animate them properly.

The problem is the order in which things are executed, and that handlers (like .hover) are stored. You wrote: "when the document is loaded, if #text doesn't have focus, remember to always toggle k and k_b on hover"

So basically you always attach the hover handler.

Here is a more complicated, but working solution, see the fiddle for the slight css and html changes:

$(document).ready(function() {
    $('#wrapper').hover(function() {
        $('#two').fadeIn(200);
    }, function() {
        if ( !$('#text').is(":focus") )
            $('#two').fadeOut(200);
    });
    $('#two').on("blur", "input", function() {
        if ( !$('#one').is(":hover") )
            $('#two').fadeOut(200);
    });
});

And the fiddle: http://jsfiddle.net/7FGK8/1/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top