Joe
Joe

Reputation: 45

Hide Input Text when click anywhere in the page

When user clicks the link, the input text shows. But how can I hide the input text when user clicks anywhere in the page (no need to click the link again to hide it)?

Here is my code

function showOrHide(zap) {
 if (document.getElementById) {
  var abra = document.getElementById(zap).style;
  if (abra.display == "block") {
   abra.display = "none";
   } else {
   abra.display = "block";
  } 
  return false;
  } else {

  return true;
 }
}

using

<a href="#" onclick="return showOrHide('menulink');">click to show or hide menu</a>
  <ul id="menulink">
   <li><input type="text" /></li>

  </ul>

Upvotes: 1

Views: 886

Answers (2)

mplungjan
mplungjan

Reputation: 178285

Try this plain JS version

function toggle(objID,show) {
  var obj = document.getElementById(objID);
  obj.style.display=show?"block":"none";
}
window.onload=function() {
  
  document.getElementById("link").onclick=function() {
    toggle("menulink",true);
    return false;
  }
  document.getElementById("menulink").onclick=function(e) {
    var event = e?e:event;
    event.stopPropagation(); // be careful here.
  }
  document.onclick=function(e) {
    var event = e?e:event;
    var target = e.target?e.target:e.srcElement;
    if (target.id !="link" && 
        target.id != "menulink") toggle("menulink",false);
  }
}
#menulink { display:none }
<a href="#" id="link">click to show or hide menu</a>
<ul id="menulink">
  <li><input type="text" /></li>
</ul>

If you have jQuery it would be

$(function(){

  $("#link").on("click",function(e) {
    e.preventDefault()
    $("#menulink").toggle(true);
  });
  $("#menulink").on("click",function(e) {
    e.stopPropagation(); // watch out here...
  });
  $(document).on("click",function(e) {
    if (e.target.id!="link") $("#menulink").toggle(false);
  });
});
#menulink { display:none }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#" id="link">click to show or hide menu</a>
<ul id="menulink">
  <li><input type="text" /></li>
</ul>

Upvotes: 1

Clyde Winux
Clyde Winux

Reputation: 295

Try this:

<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(document).mouseup(function (e)
{
var container = $("#menulink input[type=text]");

if (!container.is(e.target) 
    && container.has(e.target).length === 0) 
{
    $("#menulink input[type=text]").hide();
}
});
<script>

Source here

Upvotes: 0

Related Questions