toggle - how to make javascript object disappear when click on rest of page - Stack Overflow

How to change the following code so when clicking anywhere on the web page, the line "This is foo&

How to change the following code so when clicking anywhere on the web page, the line "This is foo" will disappear, right now I have to click "Click here" to make it disappear.

<html>
<script type="text/javascript">
<!--
    function toggle_visibility(id) {
       var e = document.getElementById(id);
       if(e.style.display == 'block')
          e.style.display = 'none';
       else
          e.style.display = 'block';
    }
//-->
</script>
<body>
<a href="#" onclick="toggle_visibility('foo');">Click here</a>
<div id="foo">This is foo</div>
</body>
</html>

How to change the following code so when clicking anywhere on the web page, the line "This is foo" will disappear, right now I have to click "Click here" to make it disappear.

<html>
<script type="text/javascript">
<!--
    function toggle_visibility(id) {
       var e = document.getElementById(id);
       if(e.style.display == 'block')
          e.style.display = 'none';
       else
          e.style.display = 'block';
    }
//-->
</script>
<body>
<a href="#" onclick="toggle_visibility('foo');">Click here</a>
<div id="foo">This is foo</div>
</body>
</html>
Share Improve this question asked Nov 7, 2013 at 14:18 Cindy TurlingtonCindy Turlington 2,5273 gold badges18 silver badges21 bronze badges 1
  • you may wish to use something other than an <a> tag for a button, otherwise you need a preventDefault(); mechanism in your function or a hack like onclick="toggle_visibility('foo');return false;" – technosaurus Commented Nov 7, 2013 at 14:56
Add a ment  | 

3 Answers 3

Reset to default 1

You'll need to bind the click event to the body element for it to fire when you click anywhere on the page.

Try to use document object for attaching event handler

document.onclick = function(){
   var e = document.getElementById('foo');
   e.style.display = ((e.style.display != 'none') ? 'none' : 'block');
};

HTML:

<body onclick="foo();">
<a href="#" onclick="toggle_visibility('foo');">Click here</a>

    <div id="foo" style="display:none;" >This is foo</div>
</body>

JS:

var b = false;

function toggle_visibility(id) {
    var e = document.getElementById(id);
     if(e.style.display == 'block')
          e.style.display = 'none';
       else
          e.style.display = 'block';
    b = true;
}

function foo() {
    var e = document.getElementById('foo');
    if(!b) e.style.display = 'none';
    b=false;
}

And this bit of css:

body,html
{
    width:100%;
    height:100%;
}

http://jsfiddle/57ZpS/8/

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745162868a4614474.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信