<div id="wrapper">
<button id="ppp">button</button>
<div id="content" style="display:none;"></div>
</div>
if i click the button,the content will be show(open),
if the content is on show(open),when i click document(except the content),the content will be close.
var $ = function (id){
return !id ? null : document.getElementById(id);
}var addEventSimple = function(obj, evt, fn) { if (obj.addEventListener){ // W3C obj.addEventListener(evt, fn, false); }else if (obj.attachEvent) // Microsoft obj.attachEvent('on' + evt, fn); } var button = $('ppp'), content = $('content'); var init = function() {}; init.handleObj = button; init.showbox = content; init.flag = false; init.allowcls = false; init.open = function () {//open the content if (this.flag == false) { this.showbox.style.display = "block"; this.flag = true; this.allowcls = true; } }; init.close = function () { // close the content if (this.flag && this.allowcls) { this.showbox.style.display = "none"; this.flag = false; this.allowcls = false; } }; init.load = function() { // button click //e = e ||window.event; //e.preventDefault(); if (this.flag) { this.close(); } else { this.open(); } }; init.clickClose = function(e) { // document click if (!this.allowcls) { return; } e = e ||window.event; var target = e.target; if (target === this.showbox) { // button return; } this.close(); }; addEventSimple(button, 'click', function (){ init.load();//the code run here OK })// error on here,but i don't know why? addEventSimple(document, 'click', function (e){ init.clickClose(e); })
code in here :http://jsfiddle.net/DCty3/
To toggle element display, you can use function like this:
There is unlimited id toggle script too:
With jQuery it will be just:
I like getting fancy with objects, here is another multifunctional method:
To use it, do something like this:
For convenience, you can add another function to enable button:
To enable function, when user clicks “outside” the box, and it closes, there is used an easy trick, by creating another element in background, that covers all area around:
CSS should make your container relative positioned and “trick box”, absolutely positioned, with maximum size of screen, and z-indexed under container like this:
And make it work like this:
The result looks like this.