commit 1148ab77cb11330ee4511b7d45a88192c081bcdc Author: Sergey Yarkov Date: Sun Oct 20 15:10:23 2019 +0300 finally diff --git a/index.html b/index.html new file mode 100644 index 0000000..1d8eb24 --- /dev/null +++ b/index.html @@ -0,0 +1,79 @@ + + + + + + + + JS Plugin + + + + + +
+ +
+ + + + + \ No newline at end of file diff --git a/script.js b/script.js new file mode 100644 index 0000000..ec4b757 --- /dev/null +++ b/script.js @@ -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 `
  • ${i.label}
  • `; + }).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'} + ] +}); \ No newline at end of file