Skip to content

Instantly share code, notes, and snippets.

@ArtemVeremienko
Created April 22, 2020 08:32
Show Gist options
  • Save ArtemVeremienko/ac4cf856d96240f4db295cc37134d4ee to your computer and use it in GitHub Desktop.
Save ArtemVeremienko/ac4cf856d96240f4db295cc37134d4ee to your computer and use it in GitHub Desktop.
Модальное диалоговое окно с формой
<h2>Кликните на кнопку ниже</h2>
<button id="btn">Кликните на кнопку, чтобы увидеть форму</button>
<div id="prompt-form-container">
<form id="prompt-form">
<div id="prompt-message"></div>
<input type="text" name="text">
<input type="submit" value="Ok">
<input type="button" name="cancel" value="Отмена">
</form>
</div>
btn.onclick = () => {
showPrompt("Введите что нибудь<br>...умное :)", (value) =>
alert("Вы ввели: " + value)
);
};
function showCover() {
let div = document.createElement('div');
div.id = 'cover-div';
document.body.style.overflowY = 'hidden';
document.body.append(div);
}
function hideCover() {
document.getElementById('cover-div').remove();
document.body.style.overflowY = '';
}
function showPrompt(html, callback) {
showCover();
let form = document.getElementById('prompt-form');
let container = document.getElementById('prompt-form-container');
document.getElementById('prompt-message').innerHTML = html;
form.text.value = '';
function complete(value) {
hideCover();
container.style.display = 'none';
document.onkeydown = null;
callback(value);
}
form.onsubmit = () => {
let value = form.text.value;
if (value == '') return false;
complete(value);
return false;
}
form.cancel.onclick = () => complete(null);
document.onkeydown = e => {
if (e.key == 'Escape') complete(null);
}
let lastElem = form.elements[form.elements.length - 1];
let firstElem = form.elements[0];
lastElem.onkeydown = e => {
if (e.key == 'Tab' && !e.shiftKey) {
firstElem.focus();
return false;
}
}
firstElem.onkeydown = e => {
if (e.key == 'Tab' && e.shiftKey) {
lastElem.focus();
return false;
}
}
container.style.display = 'block';
form.elements.text.focus();
}
html,
body {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
}
#prompt-form {
display: inline-block;
padding: 5px 5px 5px 70px;
width: 200px;
border: 1px solid black;
background: white url(https://en.js.cx/clipart/prompt.png) no-repeat left 5px;
vertical-align: middle;
}
#prompt-form-container {
display: none;
position: fixed;
top: 0;
left: 0;
z-index: 9999;
width: 100%;
height: 100%;
text-align: center;
}
#prompt-form-container::before {
display: inline-block;
height: 100%;
content: "";
vertical-align: middle;
}
#prompt-form input[name="text"] {
display: block;
margin: 5px;
width: 180px;
}
#cover-div {
position: fixed;
top: 0;
left: 0;
z-index: 9000;
width: 100%;
height: 100%;
background-color: gray;
opacity: 0.3;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment