Hello, the first time I wrote something on js, I would very much like to know whether it is possible to somehow shorten the code, combine something or improve the readability of the code. And I would also like to know: is it normal to declare such a bunch of variables, or does this indicate curvature?
Code: https://jsfiddle.net/2d46g2sc/
var bgaArea = document.getElementById('name_area'), bgUsrInputBtn = document.getElementById('user_btn'), bgApplyBtn = document.getElementById('user_btn2'), bgReverseBtn = document.getElementById('user_btn3'), bgbgRandomBtn = document.getElementById('user_btn4'), infoArea = document.getElementById('show'), bgInput, a, bgRandom; bgUsrInputBtn.onclick = function() { a = true; bgInput = prompt('Введите цвет(English or RGB only)', 'red'); bgaArea.style.background = bgInput; infoArea.innerHTML = 'Вы выбрали: ' + bgInput; bgApplyBtn.style.visibility = 'visible'; if (bgInput == null || bgInput == "") { infoArea.innerHTML = 'Вы ничего не выбрали'; bgApplyBtn.style.visibility = 'hidden'; }; }; bgbgRandomBtn.onclick = function() { a = false; bgRandom = '#' + (Math.random().toString(16)).substring(2, 8); bgaArea.style.background = bgRandom; bgApplyBtn.style.visibility = 'visible'; infoArea.innerHTML = 'Вы выбрали: ' + bgRandom; }; bgApplyBtn.onclick = function() { if (a == true) { document.body.style.background = bgInput; if (bgInput == null || bgInput == "") { alert('Не,не. Сначало надо выбрать цвет'); bgReverseBtn.style.visibility = 'hidden'; } else { bgReverseBtn.style.visibility = 'visible'; }; } else { document.body.style.background = bgRandom; bgReverseBtn.style.visibility = 'visible'; }; }; bgReverseBtn.onclick = function() { document.body.style.background = '#fff'; bgReverseBtn.style.visibility = 'hidden'; }; infoArea.innerHTML = 'Вы пока ничего не выбрали'; //list.appendChild(infoArea);
button { margin: 0; padding: 0; border: 0; } #name_area { width: 100px; height: 100px; border: 1px black solid; display: block; background-color: #000; } #user_btn, #user_btn2, #user_btn3, #user_btn4 { border-radius: 20px; width: 240px; display: inline-block; border: 1px solid #000; cursor: pointer; line-height: 1.4em; padding: 5px 20px; text-align: center; margin: 1em 0; background: transparent; } #user_btn2, #user_btn3 { visibility: hidden; } #user_btn3 { background: white; }
<div id="name_area"></div> <button id="user_btn">Ввести цвет фона квадратика</button> <button id="user_btn4">Случайный цвет</button> <button id="user_btn2">Применить к фону</button> <button id="user_btn3">Вернуть назад</button> <div id="show"></div>