Создаем всплывающую HTML-форму обратной связи с pop-up окном об успешной отправке

[vc_message color=»alert-success»]Если вам нужна всплывающая форма обратной связи для WordPress, тогда читайте эту статью:
Как сделать форму обратной связи во всплывающем окне для WordPress[/vc_message]

Будет много кода, но он будет весь рабочий, понятный и очень простой.

  1. Сделаем всплывающую форму с куки.
  2. Сделаем всплывающее окно после успешной отправки.

Изначально думал, сделать несколько разных форм, но потом решил сделать одну, а в нее включить всё, что можно. И если нужна будет какая-то упрощенная форма, то можно будет просто использовать свои настройки и не включать все возможности.

[UPD] Форму я брал с одного из рабочих сайтов, и чтобы было в ней меньше кода, взял код подписной формы. Думаю, переименовать поля в форме и добавить textarea не составит труда, поэтому из подписной формы не сложно будет сделать форму обратной связи или любую другую форму, я же оставлю код таким как он есть, иначе нужно менять еще и тексты в форме и менять стили, а мне уже лень (делаю уже, надеюсь, последний, 17-ый апдейт этого кода).

Будем использовать:

Рекомендую изучить три статьи, ссылки на которые я указал выше, весь код будет взят из них и собран в этой статье с минимальными разъяснениями.

 

Форма обратной связи с всплывающим окном о подтверждении отправления.

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">&times;</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">&times;</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">&times;</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">&times;</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>
Убирать или нет Яндекс.Метрику со своих сайтов после введения санкций против Яндекса в Украине?

Как известно, 15 мая указом президента Украины Петра Порошенко были введены санкции против России. Помимо…

Уникальная форма обратной связи с ajax на php

Самый уникальный скрипт формы обратной связи, из всех, что я встречал, нашел на этой сайте…

Делаем Fotorama адаптивной

Очень простой и крутой плагин Fotorama, но он совсем не адаптивный. Например нужно сделать, чтобы…

Определяем браузер пользователя и подставляем его название в страницу

Задача: Определить браузер пользователя и в документе подставить название его браузера вместо текста, который стоит по умолчанию.

9 комментариев

Добрый день. Спасибо за красивую форму, не разобрался как выводить ее ( кнопка или ссылка для вывода формы.) Спасибо

В данной статье поп-ап выводится автоматически через время после загрузки страницы.
В этой статье есть пример попапа с вызовом по клику на кнопке Делаем попап без плагина fancybox.

Если быстро, то надо добавить кнопку

<a id="popup" href="javascript:void(0);">Open</a>

создаем переменную

var $popUp = $('#popup');

при нажатии на кнопку показываем попап

  $popUp.on('click', function(){
    $popOverlay.fadeIn();
    $popWindow.fadeIn();
  });

чтобы при нажатии на область вне попап-окна, попап скрывался нужно после строки

if ($(event.target).closest($popWindow).length) return;

добавить код

if ($(event.target).closest($popUp).length) return;

По идее, должно работать.

Артём

Добрый день. Подскажите пожалуйста как сделать что бы форма выскакивала только один раз.
Мне дали скрипт но я не могу его применить к данной форме.

window.onkeyup = okno; // нажатие Esc, см. условие "e.keyCode==27" 
document.getElementById('popup').onclick = okno;

function okno(e) {
  if (e.target.nodeName != 'DIV' &amp;&amp; e.target.nodeName != 'FIGCAPTION' || e.keyCode==27) { // через &amp;&amp; перечисляются теги, клинкув на которые окно не будет закрыто; сюда же можно включить тег A или IFRAME 
    document.getElementById('popup').style.display='none';
    localStorage.setItem('popup1', 'none');
  }
}

if(localStorage.getItem('popup1')) {
  document.getElementById('popup').style.display='none';
}

Не знаю, это не мой скрипт. С этим лучше обратиться к фрилансерам или сюда https://stackoverflow.com/

Евгений

В HTML почти не разбираюсь, но взял за основу Ваш код, чтобы сделать всплывающее окно на главной странице у себя в офисе.
Благодаря комментариям в коде понял что куда. Супер получилось. Спасибо.

Скажите пожалуйста, а где именно прописать в коде свой Е_майл куда должно прейти уведомление, что клиент заполнил и отправил форму обратной связи.

Вы правы, нужно будет добавить в статью код для файла mail.php.
А пока вы можете найти его в статье Уникальная форма обратной связи с ajax на php.

А почему не отправляется ваша форма после нажатия кнопки «Subscribe» и не отображается «Блогодарственное окно»

Потому что форма размещена на Codepen без файла mail.php.
Если вы разместите форму на своем сервере, то она будет работать как надо.
Я бы мог добавить код, который вызывает попап при нажатии на кнопку без отправки формы, но потом еще больше людей будут писать, что попап всплывает при невалидной форме, как это исправить и тд.

Ответить