Popup form with javascript

How TO — Popup Form

Learn how to create a popup form with CSS and JavaScript.

How To Create a Popup Form

Step 1) Add HTML

Use a element to process the input. You can learn more about this in our PHP tutorial.

Example

Login

Step 2) Add CSS:

Example

/* Button used to open the contact form — fixed at the bottom of the page */
.open-button background-color: #555;
color: white;
padding: 16px 20px;
border: none;
cursor: pointer;
opacity: 0.8;
position: fixed;
bottom: 23px;
right: 28px;
width: 280px;
>

/* The popup form — hidden by default */
.form-popup display: none;
position: fixed;
bottom: 0;
right: 15px;
border: 3px solid #f1f1f1;
z-index: 9;
>

/* Add styles to the form container */
.form-container max-width: 300px;
padding: 10px;
background-color: white;
>

/* Full-width input fields */
.form-container input[type=text], .form-container input[type=password] width: 100%;
padding: 15px;
margin: 5px 0 22px 0;
border: none;
background: #f1f1f1;
>

/* When the inputs get focus, do something */
.form-container input[type=text]:focus, .form-container input[type=password]:focus background-color: #ddd;
outline: none;
>

/* Set a style for the submit/login button */
.form-container .btn background-color: #04AA6D;
color: white;
padding: 16px 20px;
border: none;
cursor: pointer;
width: 100%;
margin-bottom:10px;
opacity: 0.8;
>

/* Add a red background color to the cancel button */
.form-container .cancel background-color: red;
>

/* Add some hover effects to buttons */
.form-container .btn:hover, .open-button:hover opacity: 1;
>

Step 3) Add JavaScript:

Example

function openForm() <
document.getElementById(«myForm»).style.display = «block»;
>

function closeForm() document.getElementById(«myForm»).style.display = «none»;
>

Tip: Go to our HTML Form Tutorial to learn more about HTML Forms.

Tip: Go to our CSS Form Tutorial to learn more about how to style form elements.

Источник

How to Create a Popup Form Using JavaScript

Popup forms are a great way to have dialogs on your website. You can create popup login forms, contact forms or any other type of forms for your site. The popup button will be just under the visitor’s eye. When a user clicks on the popup button, the form will appear on the screen.

Here you can learn how to create a popup form using JavaScript.

Use the display = «block» for the openForm() and display = «none» for the closeForm() functions to show and close the form when clicked:

function openTheForm() < document.getElementById("popupForm").style.display = "block"; > function closeTheForm() < document.getElementById("popupForm").style.display = "none"; >

Example of popup form using JavaScript:

html> html> head> title>Title of the document title> style> * < box-sizing: border-box; > .openBtn < display: flex; justify-content: left; > .openButton < border: none; border-radius: 5px; background-color: #1c87c9; color: white; padding: 14px 20px; cursor: pointer; position: fixed; > .loginPopup < position: relative; text-align: center; width: 100%; > .formPopup < display: none; position: fixed; left: 45%; top: 5%; transform: translate(-50%, 5%); border: 3px solid #999999; z-index: 9; > .formContainer < max-width: 300px; padding: 20px; background-color: #fff; > .formContainer input[type=text], .formContainer input[type=password] < width: 100%; padding: 15px; margin: 5px 0 20px 0; border: none; background: #eee; > .formContainer input[type=text]:focus, .formContainer input[type=password]:focus < background-color: #ddd; outline: none; > .formContainer .btn < padding: 12px 20px; border: none; background-color: #8ebf42; color: #fff; cursor: pointer; width: 100%; margin-bottom: 15px; opacity: 0.8; > .formContainer .cancel < background-color: #cc0000; > .formContainer .btn:hover, .openButton:hover < opacity: 1; > style> head> body> h2>Popup Form h2> p>Click on the "Open Form" button to open the popup form. p> div class="openBtn"> button class="openButton" onclick="openForm()">strong>Open Form strong> button> div> div class="loginPopup"> div class="formPopup" id="popupForm"> form action="/action_page.php" class="formContainer"> h2>Please Log in h2> label for="email"> strong>E-mail strong> label> input type="text" id="email" placeholder="Your Email" name="email" required> label for="psw"> strong>Password strong> label> input type="password" id="psw" placeholder="Your Password" name="psw" required> button type="submit" class="btn">Log in button> button type="button" class="btn cancel" onclick="closeForm()">Close button> form> div> div> script> function openForm( ) < document.getElementById("popupForm").style.display = "block"; > function closeForm( ) < document.getElementById("popupForm").style.display = "none"; > script> body> html>

It is also possible to separate the modal box and close it by clicking anywhere outside of the box. For that, you just need to use the target event property which returns the element that triggered the event:

function openForm() < document.getElementById("loginPopup").style.display = "block"; > function closeForm() < document.getElementById("loginPopup").style.display = "none"; > // When the user clicks anywhere outside of the modal, close it window.onclick = function (event) < let modal = document.getElementById('loginPopup'); if (event.target == modal) < closeForm(); > >

It is not too difficult to have several Popup Forms use the data-*global attribute. The data-* attribute is used to store custom data private to the page. Here, we use a data-modal attribute:

let modalBtns = [. document.querySelectorAll(".button")]; modalBtns.forEach(function (btn) < btn.onclick = function () < let modal = btn.getAttribute('data-modal'); document.getElementById(modal).style.display = "block"; >>); let closeBtns = [. document.querySelectorAll(".close")]; closeBtns.forEach(function (btn) < btn.onclick = function () < let modal = btn.closest('.modal'); modal.style.display = "none"; >>); window.onclick = function (event) < if (event.target.className === "modal") < event.target.style.display = "none"; >>

Example of setting multiple popup forms in one page:

html> html> head> title>Title of the document title> style> .modal < display: none; position: fixed; z-index: 8; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgb(0, 0, 0); background-color: rgba(0, 0, 0, 0.4); > .modal-content < margin: 50px auto; border: 1px solid #999; width: 60%; > h2, p < margin: 0 0 20px; font-weight: 400; color: #999; > span < color: #666; display: block; padding: 0 0 5px; > form < padding: 25px; margin: 25px; box-shadow: 0 2px 5px #f5f5f5; background: #eee; > input, textarea < width: 90%; padding: 10px; margin-bottom: 20px; border: 1px solid #1c87c9; outline: none; > .contact-form button < width: 100%; padding: 10px; border: none; background: #1c87c9; font-size: 16px; font-weight: 400; color: #fff; > button:hover < background: #2371a0; > .close < color: #aaa; float: right; font-size: 28px; font-weight: bold; > .close:hover, .close:focus < color: black; text-decoration: none; cursor: pointer; > button.button < background: none; border-top: none; outline: none; border-right: none; border-left: none; border-bottom: #02274a 1px solid; padding: 0 0 3px 0; font-size: 16px; cursor: pointer; > button.button:hover < border-bottom: #a99567 1px solid; color: #a99567; > style> head> body> h2>Multiple Popup Forms h2> p> button class="button" data-modal="modalOne">Contact Us button> p> p> button class="button" data-modal="modalTwo">Send a Compliant Form button> p> div id="modalOne" class="modal"> div class="modal-content"> div class="contact-form"> a class="close">× a> form action="/"> h2>Contact Us h2> div> input class="fname" type="text" name="name" placeholder="Full name" /> input type="text" name="name" placeholder="Email" /> input type="text" name="name" placeholder="Phone number" /> input type="text" name="name" placeholder="Website" /> div> span>Message span> div> textarea rows="4"> textarea> div> button type="submit" href="/">Submit button> form> div> div> div> div id="modalTwo" class="modal"> div class="modal-content"> div class="contact-form"> span class="close">× span> form action="/"> h2>Complaint form h2> div> input class="fname" type="text" name="name" placeholder="Full name" /> input type="text" name="name" placeholder="Email" /> input type="text" name="name" placeholder="Phone number" /> input type="text" name="name" placeholder="Website" /> div> span>Message span> div> textarea rows="4"> textarea> div> button type="submit" href="/">Submit button> form> div> div> div> script> let modalBtns = [. document.querySelectorAll(".button")]; modalBtns.forEach(function (btn) < btn.onclick = function ( ) < let modal = btn.getAttribute("data-modal"); document.getElementById(modal).style.display = "block"; >; >); let closeBtns = [. document.querySelectorAll(".close")]; closeBtns.forEach(function (btn) < btn.onclick = function ( ) < let modal = btn.closest(".modal"); modal.style.display = "none"; >; >); window.onclick = function (event) < if (event.target.className === "modal") < event.target.style.display = "none"; > >; script> body> html>

The event target Property

The target property of event enterface is a reference to the object onto which the event was dispatched, opposed to the Event.currentTarget when the event handler is called during the bubbling or capturing phase.

Источник

Попап на чистом JS. Модальное окно без jQuery

Приветствую, друзья, сегодня я покажу, как создать попап на чистом js. В данном всплывающем окне вы можете разместить что угодно. Например, форму для обратной связи (как в данном примере) или любой другой контент. Так же мы реализуем несколько способов скрытие модального окна. Первый способ — скрытие попап окна при клике на фон, а второй — при клике на крестик. Пример того, что вы получите в итоге, можно посмотреть по ссылке на codepen .

HTML-структура модального окна

Для начала создадим HTML разметку для нашего всплывающего окна на чистом JavaScript. Тут все достаточно просто, так что я просто размещу код. Единственное, что стоит упомянуть — вы можете вместо формы разместить любой HTML код.

Так же вам нужно добавить кнопку, при клике на которую нужно открывать окно. В моем случае, это тег с классом ‘open-popup’ .

Стилизация всплывающего окна на чистом JS

Далее необходимо стилизовать наш попап на чистом js. CSS код так же достаточно простой. Большинство кода это вовсе стилизация формы, которая никак не влияет на само окно. Важный код для урока я вынесу в самое начало вставки с кодом. Так же я отмечу её с помощью комментариев.

/* Важная часть */ .popup__bg < position: fixed; top: 0; left: 0; width: 100%; height: 100vh; background: rgba(0,0,0,0.5); opacity: 0; // Скрываем фон и сам попап pointer-events: none; // Запрещаем ему быть целью событий transition: 0.5s all; >.popup__bg.active < // При добавлении класса 'active' opacity: 1; // Показываем фон и попап pointer-events: all; // Возвращаем события transition: 0.5s all; >.popup < position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%) scale(0); // Центрируем и масштабируем в 0 само окно background: #fff; width: 400px; padding: 25px; transition: 0.5s all; >.popup.active < // При добавлении класса 'active' transform: translate(-50%, -50%) scale(1); // Так же центрируем и плавно увеличиваем transition: 0.5s all; >/* Конец важной части */ /* Далее код для стилизации формы */ .close-popup < position: absolute; top: 10px; right: 10px; cursor: pointer; >.popup label < width: 100%; margin-bottom: 25px; display: flex; flex-direction: column-reverse; >.popup .label__text < font-size: 14px; text-transform: uppercase; font-weight: 500; color: #cfd0d3; margin-bottom: 5px; >.popup input < height: 45px; font-size: 18px; border: none; outline: none; border-bottom: 1px solid #cfd0d3; >.popup input:focus < border-bottom: 1px solid #2982ff; >.popup input:focus + .label__text < color: #2982ff; >.popup textarea < resize: none; width: 100%; height: 150px; border: none; outline: none; border-bottom: 1px solid #cfd0d3; font-size: 18px; padding-top: 5px; >.popup textarea:focus < border-bottom: 1px solid #2982ff; >.popup textarea:focus + .label__text < color: #2982ff; >.popup button < width: 100%; height: 45px; display: flex; align-items: center; justify-content: center; color: #fff; font-size: 18px; border: 2px solid #2982ff; background: #2982ff; cursor: pointer; text-transform: uppercase; transition: 0.5s all; >.popup button:hover

Показ всплывающего окна при клике

Теперь переходим к самому интересному. Будем писать JavaScript код для модального окна. Для начала, создадим переменные, в которые мы поместим все DOM-елементы, которые нам понадобятся в будущем.

let popupBg = document.querySelector('.popup__bg'); // Фон попап окна let popup = document.querySelector('.popup'); // Само окно let openPopupButtons = document.querySelectorAll('.open-popup'); // Кнопки для показа окна let closePopupButton = document.querySelector('.close-popup'); // Кнопка для скрытия окна

Далее напишем код, для появления модального окна на чистом JavaScript. Для начала, нужно повесить обработчик события клика ( addEventListener ) на каждую кнопку открытия окна. При клике — указываем, что для фона и для самого окна нужно добавить класс ‘active’ . А так же предотвращаем стандартное поведение браузера, что бы при клике на ссылку браузер не прыгал вверх странички.

openPopupButtons.forEach((button) => < // Перебираем все кнопки button.addEventListener('click', (e) =>< // Для каждой вешаем обработчик событий на клик e.preventDefault(); // Предотвращаем дефолтное поведение браузера popupBg.classList.add('active'); // Добавляем класс 'active' для фона popup.classList.add('active'); // И для самого окна >) >);

Скрытие попап окна при клике на крестик

Тут код очень простой. Указываем, что при клике на крестик, нужно убрать активные классы с фона и самого окна.

closePopupButton.addEventListener('click',() => < // Вешаем обработчик на крестик popupBg.classList.remove('active'); // Убираем активный класс с фона popup.classList.remove('active'); // И с окна >);

Прячем попап окно на чистом js при клике на фон

Теперь разберемся как спрятать попап при клике на фон. Нужно повесить обработчик клика на весь документ. Далее необходимо передать событие (е). Если цель события (клик) — это фон окна, то мы так же убираем активные классы с фона и окна.

document.addEventListener('click', (e) => < // Вешаем обработчик на весь документ if(e.target === popupBg) < // Если цель клика - фот, то: popupBg.classList.remove('active'); // Убираем активный класс с фона popup.classList.remove('active'); // И с окна >>);

Спасибо, что прочитали. Если у вас остались вопросы — задавайте их в Telegram-канале или в комментариях на YouTube. Так же буду благодарен, если вы прочитаете другие мои статьи:

Full Stack разработчик, Frontend: Vue.js (2,3) + VueX + Vue Router, Backend: Node.js + Express.js. Раньше работал с РНР, WordPress, написал несколько проектов на Laravel. Люблю помогать людям изучать что-то новое)

Источник

Читайте также:  Java try catch all exception
Оцените статью