Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide div by onclick using javascript?

I have used a javascript to show div by onclick but when i click outside div i want to hide the div. How to do it in javascript? i'm using javascript code..

<a href="javascript:;" onClick="toggle('one');">  

function toggle(one)
{
    var o=document.getElementById(one);

    o.style.display=(o.style.display=='none')?'block':'none';
}
like image 565
Jay Avatar asked Dec 13 '22 21:12

Jay


2 Answers

HTML

<a href="#" onclick="toggle(event, 'box');">show/hide</a>

Javascript

// click on the div
function toggle( e, id ) {
  var el = document.getElementById(id);
  el.style.display = ( el.style.display == 'none' ) ? 'block' : 'none';

  // save it for hiding
  toggle.el = el;

  // stop the event right here
  if ( e.stopPropagation )
    e.stopPropagation();
  e.cancelBubble = true;
  return false;
}

// click outside the div
document.onclick = function() {
  if ( toggle.el ) {
    toggle.el.style.display = 'none';
  }
}
like image 113
25 revs, 4 users 83% Avatar answered Jan 04 '23 22:01

25 revs, 4 users 83%


you can use blur() function when you clicked somewhere else

$("#hidelink").click(function() {
    $("#divtoHide").show();
});

$("#hidelink").blur(function() {
    $("#divtoHide").hide();
});
like image 34
D.J Avatar answered Jan 04 '23 22:01

D.J