Skip to content

Commit e991008

Browse files
authored
Create customSelect.js
1 parent 655b76c commit e991008

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

customSelect.js

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
const generateSelect = (target) => {
2+
3+
//add custom select structure
4+
function wrap(el, classes, ids) {
5+
let wrapper = document.createElement( 'div' );
6+
let innerWrapper = document.createElement( 'ul' );
7+
let label = document.createElement( 'div' );
8+
el.parentNode.insertBefore(wrapper, el);
9+
let classList = classes.split(' ').filter(v => v !== '')
10+
wrapper.classList.add( ...classList );
11+
wrapper.setAttribute('id', ids);
12+
innerWrapper.classList.add( 'options' );
13+
label.classList.add( 'label' );
14+
wrapper.appendChild(el);
15+
wrapper.appendChild(label);
16+
wrapper.appendChild(innerWrapper);
17+
}
18+
19+
//get all select elements
20+
const select = document.querySelectorAll( target );
21+
for(e of select){
22+
23+
//get select classes
24+
const classes = e.classList.value;
25+
const ids = e.getAttribute('id');
26+
27+
// add wrapper in select element
28+
wrap(e, `select ${classes}`, ids);
29+
30+
// add custom select options
31+
const options = e.querySelectorAll( 'option' );
32+
for(let i = 0; i < options.length; i++){
33+
let html = `<li value='${options[i].value}'>${options[i].innerText}</li>`;
34+
e.parentNode.querySelector( '.options' ).innerHTML += html;
35+
}
36+
37+
//add options and label
38+
e.parentNode.querySelector( '.label' ).innerHTML = e.getAttribute('aria-placeholder') || 'select';
39+
40+
}
41+
42+
//change label value when user select option
43+
let selectLabel = document.querySelectorAll('.select .label');
44+
selectLabel.forEach(e => {
45+
e.addEventListener('click', () => {
46+
if(e.parentNode.classList.contains('active')){
47+
e.parentNode.classList.remove('active');
48+
}else{
49+
e.parentNode.classList.add('active');
50+
}
51+
});
52+
});
53+
54+
//change select value when user select option
55+
let selectOptions = document.querySelectorAll('.select .options > li');
56+
selectOptions.forEach(e => {
57+
e.addEventListener('click', () => {
58+
e.closest(".select").querySelector('.label').innerHTML = e.innerHTML;
59+
e.closest(".select").classList.remove('active');
60+
e.closest(".select").querySelector('select').value = e.getAttribute("value");
61+
});
62+
});
63+
64+
//remove active class when user click outside
65+
let outsideSelect = document.querySelectorAll('.select');
66+
outsideSelect.forEach(elm => {
67+
document.addEventListener('click', (e) => {
68+
if(!elm.contains(e.target)){
69+
elm.classList.remove('active')
70+
}
71+
})
72+
})
73+
74+
}
75+
76+
document.addEventListener('DOMContentLoaded', () => {
77+
generateSelect('select');
78+
})

0 commit comments

Comments
 (0)