html:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>js dev test</title> <link href="css/style.css" rel="stylesheet"> <script src="js/script.js"></script> </head> <body> <div id="myToolbar" class="toolbar"> <span class="toolbar-item">0</span> <span class="toolbar-item">1</span> <span class="toolbar-item">2</span> <span class="toolbar-item">3</span> </div> </body> </html>
css:
.toolbar { background-color: #ccc; height: 50px; padding: 5px; margin: 5px; } .toolbar-item { display: inline-block; height: 50px; width: 50px; background-color: #00f; margin: 5px; } .active { background-color: #ff0; } .disabled { background-color: #555; }
js:
var oojs = (function (oojs) { var createToolbarItem = function (itemElement) { var item = { toggleActiveState: function () { this.activated = !this.activated; } }; Object.defineProperties(item, { el: { value: itemElement }, enabled: { get: function () { return !this.el.classList.contains('disabled'); }, set: function (value) { if (value) { this.el.classList.remove('disabled'); } else { this.el.classList.add('disabled'); } } }, activated: { get: function () { return this.el.classList.contains('active'); }, set: function (value) { if (value) { this.el.classList.add('active'); } else { this.el.classList.remove('active'); } } } }); return item; }; var createToolbarItems = function (itemElements) { var items = []; [].forEach.call( itemElements, function( el, index, array ) { var item = createToolbarItem(el); items.push(item); }); return items; }; oojs.createToolbar = function (elementId) { var element = document.getElementById(elementId); if (!element) { element = document.createElement('div'); element.id = elementId; element.className = 'toolbar'; } var items = element.querySelectorAll('.toolbar-item'); var toolbar = { add: function (options) { var span = document.createElement('span'); span.className = 'toolbar-item'; this.el.appendChild(span); var item = createToolbarItem(span); this.items.push(item); }, remove: function(index) { var len = this.items.length; if(index > len || index < 0) { throw new Error('Index is out '); } var item = this.items[index]; this.items.splice(index, 1); this.el.removeChild(item.el); item = null; }, appendTo: function (parentElement) { parentElement.appendChild(this.el); } }; Object.defineProperties(toolbar, { el: { value: element }, items: { value: createToolbarItems(items), enumerable: true } }); return toolbar; }; return oojs; }(oojs || {})); /* var toolbar = oojs.createToolbar('myToolbar'); toolbar.items[0].enabled = false; toolbar.items[0].enabled = true; toolbar.items[1].activated = true; toolbar.items[1].activated = false; toolbar.items[2].toggleActiveState(); toolbar.add(); toolbar.remove(2); var toolbar2 = oojs.createToolbar('myToolbar2'); toolbar2.appendTo(document.body); toolbar2.add(); */