This commit is contained in:
Sergey Yarkov 2019-10-20 15:10:23 +03:00
commit 1148ab77cb
2 changed files with 129 additions and 0 deletions

79
index.html Normal file
View File

@ -0,0 +1,79 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>JS Plugin</title>
<style>
* {
box-sizing: border-box;
}
body {
font-family: sans-serif;
}
.app {
width: 100%;
height: 100vh;
overflow: hidden;
display: flex;
justify-content: center;
padding-top: 50px;
}
.dropdown {
position: relative;
width: 400px;
}
.dropdown.open .dropdown__menu {
display: block;
}
.dropdown__label {
padding: 10px 10px;
border: 1px solid rgb(34, 34, 34);
width: 100%;
cursor: pointer;
}
.dropdown__menu {
list-style: none;
margin: 0;
padding: 0;
display: none;
border-right: 1px solid;
border-left: 1px solid;
position: absolute;
width: 100%;
top: 39px;
}
.dropdown__menu li {
padding: 10px 10px;
border-bottom: 1px solid;
}
.dropdown__menu li:hover {
background-color: rgba(0, 0, 0, .2);
cursor: pointer;
}
</style>
</head>
<body>
<div class="app">
<div class="dropdown" id="dropdown">
<div class="dropdown__label"></div>
<ul class="dropdown__menu"></ul>
</div>
</div>
<script src="./script.js"></script>
</body>
</html>

50
script.js Normal file
View File

@ -0,0 +1,50 @@
class Dropdown {
constructor(selector, options) {
this.$el = document.querySelector(selector);
this.items = options.items;
this.$el.querySelector('.dropdown__label').textContent = this.items[0].label;
this.$el.addEventListener('click', event => {
if (event.target.classList.contains('dropdown__label')) {
if (this.$el.classList.contains('open')) {
this.close();
} else {
this.open();
}
} else if (event.target.tagName.toLowerCase() === 'li') {
this.select(event.target.dataset.id);
}
});
const itemsHTML = this.items.map(i => {
return `<li data-id="${i.id}">${i.label}</li>`;
}).join(' ');
this.$el.querySelector('.dropdown__menu').insertAdjacentHTML('afterbegin', itemsHTML);
}
select(id) {
const item = this.items.find(i => i.id === id);
this.$el.querySelector('.dropdown__label').textContent = item.label;
this.close();
}
open() {
this.$el.classList.add('open');
}
close() {
this.$el.classList.remove('open');
}
}
const dropdown = new Dropdown('#dropdown', {
items: [
{label: 'Москва', id: 'msk'},
{label: 'Санкт-Петербург', id: 'spb'},
{label: 'Новосибирск', id: 'nsk'},
{label: 'Краснодар', id: 'krdr'}
]
});