0

I want to hide a div on focusout of its child elements.say,

lets have username and password field in a div,it will be minimized initially, user will clicks opens the div then if user click anywhere outside the div should close the mydiv

<body>

<div id="mydiv" onblur="alert('hi');" tabindex="1" style="border: 1px solid black;">click off me to activate onblur
    <br/>
    username: <input type="text" name="username" onblur="alert('hi');" tabindex="1" />
    <br/>
   Password: <input type="text" name="password" />

    </div>
</body>

(see the JS fiddle : http://jsfiddle.net/vC7Rb/1/)

I tried putting onblur for both div as well as text field but that require common function call from which I need to check if any of the element is still have focus and then only hide the div.thats seems too much, so is there any simple way to do this.

I want implement this in pure javascript code and it should be compatible in all browser(IE,firefox,chrome).

Lohith MV
  • 3,798
  • 11
  • 31
  • 44

1 Answers1

0

In general you are asking about how to detect a click outside an element. That question is asked and answered nicely here. In addition, here is a fiddle showing how to handle both the hiding and reshowing nicely with your use-case. The only thing I really added was showing that whatever button/methodology you use to reshow the username/password div will need to use the same sort of event.stopPropagation() to avoid re-hiding what you are trying to show.

HTML:

<button onclick="document.getElementById('loginContainer').style.display='block';event.stopPropagation();">Show Login</button>
<div id="loginContainer" onclick="containerClicked(event)" style="border:1px solid black">
    <div><span>User Name:</span><input id="username" /></div>
    <div><span>Password:</span><input id="password" type="password"/></div>
</div>
<div style="border:1px solid red">Some other div on document</div>

JS:

document.onclick = function(){
    console.warn('doc clicked');
    document.getElementById('loginContainer').style.display = 'none';
}
function containerClicked(ev)
{
    console.warn('clicked');
    ev.stopPropagation();
}
Community
  • 1
  • 1
purgatory101
  • 6,494
  • 1
  • 20
  • 21