I have an input box that successfully toggles a hidden div. However, I also want the div to hide when the user clicks anything other than the div itself. How might I do this?
html
<input id="inputID" type="text" readonly />
<div id="divID"></div>
js
var divObj = document.getElementById('divID');
var inputObj = document.getElementById('inputID');
inputObj.addEventListener('click', toggleDiv, false);
function toggleDiv(){
divObj.style.display = (divObj.style.display == 'none') ? 'block' : 'none';
}
Create an event listener on
document.bodyelement and check if the event originated from an element inside your div and if not hide it. You can ease this job up a bit by not checking the origin but simply preventing click events from inside your div from bubbling up by calling.stopPropagation()on the event object.Demo: http://jsfiddle.net/ThiefMaster/D7YnS/