Last active
January 4, 2016 18:09
-
-
Save aclave1/8659028 to your computer and use it in GitHub Desktop.
Simple Javascript dropdown box
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* AddDropdown : appends a dropdown box to an element, and provides a callback to further style the element and the dropdown | |
* | |
@param elem an html node object, or the id of an html node object | |
@param css an object literal containing css to apply to the dropdown box | |
@param callback allows the user to do more with the dropdown box | |
*/ | |
function AddDropdown(elem,css,callback){ | |
//you can pass this method a string, or an object that was selected using getElementById | |
this.elem = (typeof elem === "string") ? document.getElementById("elem") : elem; | |
if(elem.drop){ | |
elem.removeChild(elem.drop); | |
} | |
this.css = css; | |
//create the div for the dropdown | |
var dc = document.createElement('div'); | |
dc.className = "autoDropDown"; | |
//copies every property in the css object onto the dropdown | |
for(var k in this.css){ | |
dc.style[k] = this.css[k]; | |
} | |
//this gives elem a handy reference to the dropdown element | |
this.elem.drop = dc; | |
this.elem.appendChild(dc); | |
callback(this.elem); | |
} | |
//lets say we have a button called dropButton which we want to trigger creation of our dropdown | |
// | |
dropButton.addEventListener("click",function(e){ | |
e.stopPropagation(); | |
//this is us actually using the AddDropDown function | |
AddDropdown( | |
//dropcontainer is the element I want to add a dropdown to. | |
dropcontainer, | |
//this is the object containing our css properties | |
{ | |
"height":"240px", | |
"width":"300px", | |
"background":"#cccccc" | |
}, | |
//this begins the callback, el is the HTML Node which we added the dropdown to. | |
function(el){ | |
//we want this dropdown to go away whenever we click outside of it! | |
document.body.addEventListener("click",function(){ | |
if(el.drop){ | |
el.removeChild(el.drop); | |
el.drop = false; | |
} | |
}); | |
//BUT! we want click events inside of our dropdown to not remove it | |
el.drop.addEventListener("click",function(e){ | |
e.stopPropagation(); | |
}); | |
} | |
); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment