Skip to content

Instantly share code, notes, and snippets.

@MichaelaIvanova
Created August 2, 2015 11:10
Show Gist options
  • Save MichaelaIvanova/a8c0925462674a576dd2 to your computer and use it in GitHub Desktop.
Save MichaelaIvanova/a8c0925462674a576dd2 to your computer and use it in GitHub Desktop.
function solve() {
return function (selector) {
var selectedList = $(selector);
selectedList.hide();
var childrenSelectedList = selectedList.children();
var numberOfChildren = childrenSelectedList.length;
var defaultText = 'Select value';
var dropDownList = $('<div>').addClass('dropdown-list');
var divCurrent = $('<div class="current" data-value="">').text(defaultText);
var container = $('<div class="options-container">')
.css({
'position':'absolute',
'display':'none'
});
var divToAppend = $('<div>').addClass('dropdown-item');
for(var i = 0; i < numberOfChildren; i+=1){
var currentDiv = divToAppend.clone();
var currentChild = $(childrenSelectedList[i]);
var innerText = currentChild.text();
var value = currentChild.attr('value');
currentDiv.attr('value', value);
currentDiv.attr('data-index', i);
currentDiv.text(innerText);
currentDiv.hide();
currentDiv.appendTo(container);
}
dropDownList.on('click','.current', function(){
var clicked = $(this);
var nextAll =clicked.nextAll();
nextAll.css('display','');
nextAll.children().css('display','');
clicked.text(defaultText);
});
container.on('click', function(ev){
var clicked = $(ev.target); // the element of the class dropdown-item
var txt = $(clicked).text();
divCurrent.text(txt); // change text of current
container.css('display','none'); //hide them again
});
selectedList.appendTo(dropDownList);
divCurrent.appendTo(dropDownList);
container.appendTo(dropDownList);
dropDownList.appendTo($('body'));
};
}
module.exports = solve;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment