Если вам нужна всплывающая форма обратной связи для WordPress, тогда читайте эту статью:
Как сделать форму обратной связи во всплывающем окне для WordPress
Будет много кода, но он будет весь рабочий, понятный и очень простой.
- Сделаем всплывающую форму с куки.
- Сделаем всплывающее окно после успешной отправки.
Изначально думал, сделать несколько разных форм, но потом решил сделать одну, а в нее включить всё, что можно. И если нужна будет какая-то упрощенная форма, то можно будет просто использовать свои настройки и не включать все возможности.
[UPD] Форму я брал с одного из рабочих сайтов, и чтобы было в ней меньше кода, взял код подписной формы. Думаю, переименовать поля в форме и добавить textarea
не составит труда, поэтому из подписной формы не сложно будет сделать форму обратной связи или любую другую форму, я же оставлю код таким как он есть, иначе нужно менять еще и тексты в форме и менять стили, а мне уже лень (делаю уже, надеюсь, последний, 17-ый апдейт этого кода).
Будем использовать:
- Универсальный скрипт формы обратной связи
- Попап без плагина fancybox
- Валидация HTML-формы без использования скриптов и php
Рекомендую изучить три статьи, ссылки на которые я указал выше, весь код будет взят из них и собран в этой статье с минимальными разъяснениями.
Форма обратной связи с всплывающим окном о подтверждении отправления.
HTML
В head подключаем нужные шрифты с Google Fonts, Bootstrap и FontAwesome (при необходимости, это не обязательно)
<link href="https://fonts.googleapis.com/css?family=Lato:400,700,900" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Titillium+Web:400,700,900" rel="stylesheet"> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
Основной HTML будет такого вида (все элементы и классы не являются обязательными у вас может быть совсем другой код, мой код взят из фрагмента рабочего сайта и немного упрощен для примера, но могут присутствовать лишние элементы):
<div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <h1>Contact Form</h1> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Maxime repellat asperiores natus unde quos consequuntur aliquid temporibus doloremque nihil nulla quidem, expedita hic nobis ipsam quia fugiat. Sunt, maxime, fugit!</p> <div class="popup-overlay"><!-- //оверлей - отображение формы на затемненном фоне --> <div class="popWindow subscribe_window"><!-- //основное окно формы Подписки --> <p class="subcsribe-text">Subscribe to receive news and information</p> <form class="subscribe-form" autocomplete="off"> <div> <input type="text" id="name-subscribe" name="Name" placeholder=" " required> <label for="name-subscribe">Name <span>*</span></label> </div> <div> <input type="email" id="email-subscribe" name="E-mail" placeholder=" " required> <label for="email-subscribe">Email <span>*</span></label> </div> <div class="aligncenter"> <button type="submit" class="btn"><i class="fa fa-check" aria-hidden="true"></i> Subscribe</button> </div> <div class="req-fields"><sup>*</sup> required fields</div> </form> <div class="close-btn">×</div> </div><!-- /subscribe_window --> <div class="popWindow thank_you_window"><!-- //благодарственное окно после успешной отправки формы --> <p class="thank_you_title">Thank you for subscribing!</p> <p class="thank_you_body">We've sent some useful tips to your email. Go ahead and check them now!</p> <div class="close-btn">×</div> </div><!-- /thank_you_window --> </div><!-- /popup-overlay --> </div> </div> </div>
CSS стили
Стили также взяты с рабочего примера, и не являются обязательными, используйте свои классы и стили, создавайте уникальный красивый дизайн.
/* Стили для затемнения фона */ .popup-overlay { display: none; position: fixed; left: 0; top: 0; right: 0; bottom: 0; background: rgba(255, 186, 0, 0.7); z-index: 100; } /* Основные стили для всплывающего окна */ .popWindow{ display: none; background-color: #161613; color: #fff; width: 90%; max-width: 720px; padding: 40px 30px; position: absolute; top: 50%; left: 50%; margin-left: -360px; margin-top: -185px; text-align: center; box-shadow: 0 0 30px rgba(18, 17, 12, 0.5); } /* Стили для адаптивности всплывающего окна */ @media only screen and (max-width : 800px) { .popWindow { margin-left: -45%; } } /* Кнопка закрыть всплывающее окно */ .close-btn { position: absolute; top: 0; right: 0; font-size: 40px; line-height: 20px; cursor: pointer; color: #999; padding: 10px; } /* Просто текст */ .subscribe_window .subcsribe-text { font-size: 18px; text-align: center; text-transform: uppercase; color: #fff; margin: 0 0 40px; position: relative; padding: 0 50px; z-index: 10; } /* Текст */ .subscribe_window .req-fields { color: #676767; text-align: left; } /* Стили формы */ .subscribe-form { width: 100%; max-width: 300px; margin: 0 auto; } .subscribe-form div { position: relative; } .subscribe-form input { border: 1px solid #3d3d3d; width: 100%; font-family: "Lato", sans-serif; font-size: 16px; line-height: 32px; padding: 5px 20px; margin-bottom: 20px; outline: none; background: #2e2e2b; color: #fff; border-radius: 4px; } .btn { color: #161613; background-color: #ffba00; padding: 10px 50px; text-align: center; font-size: 13px; border: 1px solid #ffba00; box-shadow: none; display: inline-block; text-transform: uppercase; text-decoration: none; display: inline-block; -webkit-transition: 0.4s; transition: 0.4s; } .btn:hover, .btn:focus { background-color: #ffba00; color: #fff; text-decoration: none; } .subscribe-form .btn { font-size: 24px; line-height: 54px; border: none; width: 100%; padding: 10px; font-weight: 700; text-align: center; outline: none; border-radius: 4px; } .subscribe-form .btn:hover { background-color: #e6a700; } .subscribe-form .btn i { font-size: 28px; margin-right: 7px; } .subscribe-form label { color: #fff; position: absolute; top: 12px; left: 20px; -webkit-transition: 0.28s; transition: 0.28s; } .subscribe-form label span { color: #ffba00; } .subscribe-form input:focus + label { left: -62px; font-size: 12px; } .subscribe-form input:invalid { box-shadow: none; } .subscribe-form input:valid { border: 1px solid #161613; } .subscribe-form input:valid + label { left: -62px; font-size: 12px; } .subscribe-form input:invalid:not(:focus):not(:placeholder-shown) { border: 1px solid #d3362a; } .subscribe-form input:invalid:not(:focus):not(:placeholder-shown) + label { left: -62px; font-size: 12px; } @media only screen and (max-width : 480px) { .subscribe_window{ top: 5%; margin-top: 0; } .subscribe_window .subcsribe-text{ padding: 0; } .subscribe-form input:focus + label{ left: 20px; top: -18px; } .subscribe-form input:valid + label{ left: 20px; top: -18px; } .subscribe-form input:invalid:not(:focus):not(:placeholder-shown) + label{ left: 20px; top: -18px; } } /* Стили для текста внутри благодарственного окна после успешной отправки */ .thank_you_window .thank_you_title { font-family: "Titillium Web", sans-serif; color: #fff; font-size: 32px; line-height: 50px; font-weight: 700; margin-bottom: 10px; } .thank_you_window .thank_you_body { font-family: "Titillium Web", sans-serif; color: #fff; font-size: 24px; font-weight: 400; }
JavaScript код
Обязательно подключаем jQuery
:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
Если вы хотите использовать в форме куки, то нужно обязательно подключить jquery.cookie.min.js
.
Скачать скрипт jquery.cookie.min.js
можно здесь.
Про пример использования куки почитайте здесь.
// PopUp Form and thank you popup after sending message var $popOverlay = $(".popup-overlay"); var $popWindow = $(".popWindow"); var $subscribeWindow = $(".subscribe_window"); var $popThankYouWindow = $(".thank_you_window"); var $popClose = $(".close-btn"); $(function() { // Close Pop-Up after clicking on the button "Close" $popClose.on("click", function() { $popOverlay.fadeOut(); $popWindow.fadeOut(); }); // Close Pop-Up after clicking on the Overlay $(document).on("click", function(event) { if ($(event.target).closest($popWindow).length) return; $popOverlay.fadeOut(); $popWindow.fadeOut(); event.stopPropagation(); }); // Form Subscribe $(".subscribe-form").submit(function() { var th = $(this); $.ajax({ type: "POST", url: "mail.php", data: th.serialize() }).done(function() { // после успешной отправки скрываем форму подписки и выводим окно с благодарностью за заполнение формы $subscribeWindow.fadeOut(); $popThankYouWindow.fadeIn(); // используем куки на 30 дней, если человек заполнил форму // для куки обязательно должен быть подключен jquery.cookie.min.js $.cookie('hideTheModal', 'true', { expires: 30 }); // очищаем форму setTimeout(function() { th.trigger("reset"); }, 1000); }); return false; }); });
Ниже функция для всплывающего окна.
Если куки не нужны, тогда добавьте этот код под основным кодом скрипта.
// используйте этот код, если нужно появление формы без куки $(window).load(function() { setTimeout(function() { $popOverlay.fadeIn(); $subscribeWindow.fadeIn(); }, 2000); });
Если вы хотите использовать куки, тогда подключайте код ниже, но не забудьте подключить скрипт jquery.cookie.min.js
// или используйте этот код, если нужно появление формы с куки и вы подключали jquery.cookie.min.js $(window).load(function() { // задаем переменную для cookie var hideTheModal = $.cookie('hideTheModal'); // если cookie не установлено... if(hideTheModal == null){ // Через 2 секунды появляется контактная форма setTimeout(function() { $popOverlay.fadeIn(); $subscribeWindow.fadeIn(); }, 2000); } });
Рабочий пример:
See the Pen HTML Pop-up Contact Form by Denis (@deniscreative) on CodePen.0
Готовая HTML-страница c формой обратной связи с использованием куки:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Pop-up Contact Form</title> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <link href="https://fonts.googleapis.com/css?family=Lato:400,700,900" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Titillium+Web:400,700,900" rel="stylesheet"> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"> <style> /* Стили для затемнения фона */ .popup-overlay { display: none; position: fixed; left: 0; top: 0; right: 0; bottom: 0; background: rgba(255, 186, 0, 0.7); z-index: 100; } /* Основные стили для всплывающего окна */ .popWindow{ display: none; background-color: #161613; color: #fff; width: 90%; max-width: 720px; padding: 40px 30px; position: absolute; top: 50%; left: 50%; margin-left: -360px; margin-top: -185px; text-align: center; box-shadow: 0 0 30px rgba(18, 17, 12, 0.5); } /* Стили для адаптивности всплывающего окна */ @media only screen and (max-width : 800px) { .popWindow { margin-left: -45%; } } /* Кнопка закрыть всплывающее окно */ .close-btn { position: absolute; top: 0; right: 0; font-size: 40px; line-height: 20px; cursor: pointer; color: #999; padding: 10px; } /* Просто текст */ .subscribe_window .subcsribe-text { font-size: 18px; text-align: center; text-transform: uppercase; color: #fff; margin: 0 0 40px; position: relative; padding: 0 50px; z-index: 10; } /* Текст */ .subscribe_window .req-fields { color: #676767; text-align: left; } /* Стили формы */ .subscribe-form { width: 100%; max-width: 300px; margin: 0 auto; } .subscribe-form div { position: relative; } .subscribe-form input { border: 1px solid #3d3d3d; width: 100%; font-family: "Lato", sans-serif; font-size: 16px; line-height: 32px; padding: 5px 20px; margin-bottom: 20px; outline: none; background: #2e2e2b; color: #fff; border-radius: 4px; } .btn { color: #161613; background-color: #ffba00; padding: 10px 50px; text-align: center; font-size: 13px; border: 1px solid #ffba00; box-shadow: none; display: inline-block; text-transform: uppercase; text-decoration: none; display: inline-block; -webkit-transition: 0.4s; transition: 0.4s; } .btn:hover, .btn:focus { background-color: #ffba00; color: #fff; text-decoration: none; } .subscribe-form .btn { font-size: 24px; line-height: 54px; border: none; width: 100%; padding: 10px; font-weight: 700; text-align: center; outline: none; border-radius: 4px; } .subscribe-form .btn:hover { background-color: #e6a700; } .subscribe-form .btn i { font-size: 28px; margin-right: 7px; } .subscribe-form label { color: #fff; position: absolute; top: 12px; left: 20px; -webkit-transition: 0.28s; transition: 0.28s; } .subscribe-form label span { color: #ffba00; } .subscribe-form input:focus + label { left: -62px; font-size: 12px; } .subscribe-form input:invalid { box-shadow: none; } .subscribe-form input:valid { border: 1px solid #161613; } .subscribe-form input:valid + label { left: -62px; font-size: 12px; } .subscribe-form input:invalid:not(:focus):not(:placeholder-shown) { border: 1px solid #d3362a; } .subscribe-form input:invalid:not(:focus):not(:placeholder-shown) + label { left: -62px; font-size: 12px; } @media only screen and (max-width : 480px) { .subscribe_window{ top: 5%; margin-top: 0; } .subscribe_window .subcsribe-text{ padding: 0; } .subscribe-form input:focus + label{ left: 20px; top: -18px; } .subscribe-form input:valid + label{ left: 20px; top: -18px; } .subscribe-form input:invalid:not(:focus):not(:placeholder-shown) + label{ left: 20px; top: -18px; } } /* Стили для текста внутри благодарственного окна после успешной отправки */ .thank_you_window .thank_you_title { font-family: "Titillium Web", sans-serif; color: #fff; font-size: 32px; line-height: 50px; font-weight: 700; margin-bottom: 10px; } .thank_you_window .thank_you_body { font-family: "Titillium Web", sans-serif; color: #fff; font-size: 24px; font-weight: 400; } </style> </head> <body> <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <h1>Contact Form</h1> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Maxime repellat asperiores natus unde quos consequuntur aliquid temporibus doloremque nihil nulla quidem, expedita hic nobis ipsam quia fugiat. Sunt, maxime, fugit!</p> <div class="popup-overlay"><!-- //оверлей - отображение формы на затемненном фоне --> <div class="popWindow subscribe_window"><!-- //основное окно формы Подписки --> <p class="subcsribe-text">Subscribe to receive news and information</p> <form class="subscribe-form" autocomplete="off"> <div> <input type="text" id="name-subscribe" name="Name" placeholder=" " required> <label for="name-subscribe">Name <span>*</span></label> </div> <div> <input type="email" id="email-subscribe" name="E-mail" placeholder=" " required> <label for="email-subscribe">Email <span>*</span></label> </div> <div class="aligncenter"> <button type="submit" class="btn"><i class="fa fa-check" aria-hidden="true"></i> Subscribe</button> </div> <div class="req-fields"><sup>*</sup> required fields</div> </form> <div class="close-btn">×</div> </div><!-- /subscribe_window --> <div class="popWindow thank_you_window"><!-- //благодарственное окно после успешной отправки формы --> <p class="thank_you_title">Thank you for subscribing!</p> <p class="thank_you_body">We've sent some useful tips to your email. Go ahead and check them now!</p> <div class="close-btn">×</div> </div><!-- /thank_you_window --> </div><!-- /popup-overlay --> </div> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="http://maxcdn.denis-creative.com/jquery.cookie.min/jquery.cookie.min.js"></script><!-- этот скрипт скачайте и добаьте локально, если нужны куки --> <script> // PopUp Form and thank you popup after sending message var $popOverlay = $(".popup-overlay"); var $popWindow = $(".popWindow"); var $subscribeWindow = $(".subscribe_window"); var $popThankYouWindow = $(".thank_you_window"); var $popClose = $(".close-btn"); $(function() { // Close Pop-Up after clicking on the button "Close" $popClose.on("click", function() { $popOverlay.fadeOut(); $popWindow.fadeOut(); }); // Close Pop-Up after clicking on the Overlay $(document).on("click", function(event) { if ($(event.target).closest($popWindow).length) return; $popOverlay.fadeOut(); $popWindow.fadeOut(); event.stopPropagation(); }); // Form Subscribe $(".subscribe-form").submit(function() { var th = $(this); $.ajax({ type: "POST", url: "mail.php", data: th.serialize() }).done(function() { // после успешной отправки скрываем форму подписки и выводим окно с благодарностью за заполнение формы $subscribeWindow.fadeOut(); $popThankYouWindow.fadeIn(); // используем куки на 30 дней, если человек заполнил форму // для куки обязательно должен быть подключен jquery.cookie.min.js $.cookie('hideTheModal', 'true', { expires: 30 }); // очищаем форму setTimeout(function() { th.trigger("reset"); }, 1000); }); return false; }); }); // используйте этот код, если нужно появление формы с куки и вы подключали jquery.cookie.min.js $(window).load(function() { // задаем переменную для cookie var hideTheModal = $.cookie('hideTheModal'); // если cookie не установлено... if(hideTheModal == null){ // Через 2 секунды появляется контактная форма setTimeout(function() { $popOverlay.fadeIn(); $subscribeWindow.fadeIn(); }, 2000); } }); </script> </body> </html>