3

In the code below if you click on <input type="text" id="one" /> and a "red block" appears. If you focus out then the "red block" disappears.

How do I make it so that focusout wont fire if "red block" or <input type="text" id="two" /> are the next focused elements?

Demo

JavaScript

$('#one').focus(function () {
    $('#divRemove').show();
});

$('#one').focusout(function () {
    $('#divRemove').hide();
});

$('#divRemove').click(function(){
    alert($(this).text());    
});

HTML

<input type="text" id="one" />_______
<input type="text" id="two" />
<br/>
<br/>
<div id="divRemove" style="width:100px;height:100px;background:red; display:none;">remove on focus out</div>
andyb
  • 43,435
  • 12
  • 121
  • 150
Hello-World
  • 9,277
  • 23
  • 88
  • 154

1 Answers1

3

You can put the focus on both #one and #two

$('#one,#two').focus(function () {
    $('#divRemove').show();
}).focusout(function () {
    $('#divRemove').hide();
});

DEMO

Update

You can't really focus a div unless you give it a custom index like this with tabindex="0"

<div id="divRemove" tabindex="0"

and then in jQuery do this

$('#one,#two,#divRemove').focus(function () {
    $('#divRemove').show();
}).focusout(function () {
    $('#divRemove').hide();
});

DEMO

Anton
  • 32,245
  • 5
  • 44
  • 54
  • great thanks so much - one more thing what if the red div had other elements in it. would that apply toall its children to no close? – Hello-World Oct 08 '13 at 08:22
  • 1
    `+1` although you could chain the event handlers to avoid repeating the selector – andyb Oct 08 '13 at 08:22
  • @Hello-World i think so, it should not be a problem – Anton Oct 08 '13 at 08:23
  • hi - can you help with this please - if I put elements in the div then it closes on the second element in focus - thanks http://jsfiddle.net/ukve6/8/ – Hello-World Oct 08 '13 at 08:31
  • @Hello-World Take away focusout for `oneA,oneB,oneC` like this http://jsfiddle.net/Alfie/ukve6/10/ – Anton Oct 08 '13 at 08:34