Валидация JS
Валидация email
1 2 3 4 5 |
function validationEmail(email) { pattern = /^([a-z0-9_\.-])+@[a-z0-9-]+\.([a-z]{2,4}\.)?[a-z]{2,4}$/i; return pattern.test(email.val()); } |
Валидация email
1 2 3 4 5 |
function validationEmail(email) { pattern = /^([a-z0-9_\.-])+@[a-z0-9-]+\.([a-z]{2,4}\.)?[a-z]{2,4}$/i; return pattern.test(email.val()); } |
У нас есть форма
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<div class="services_form_right"> <form class="services_form" id="paving_and_laying"> <input type="text" name="name" placeholder="Имя"> <input type="email" name="email" placeholder="E-mail"> <input type="tel" name="phone" placeholder="Телефон"> <textarea name="message" placeholder="Комментарий к заказу"></textarea> <div class="box_agree"> <input type="checkbox" name="agree" id="agree" class="checkbox"> <label for="agree" class="check">Даю согласие на обработку персональных данных</label> </div> <div class="services_btn"> <button type="submit" class="btn">Расчитать заказ</button> </div> </form> </div> |
js’ка
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
$("form#paving_and_laying").on('submit', function(event){ event.preventDefault(); form = $(this); $.ajax({ type: "POST", url: "/make.php", data: $(this).serializeArray(), success: function(msg) { json = $.parseJSON(msg); form.find('.requiredInputError').removeClass('requiredInputError'); if (json.result) { form.parent('.services_form_right').addClass('success').html(json.msg); form.remove(); } else { if (json.errors) { json.errors.forEach(function(item) { if (item == 'agree') { form.children('div').children('label').addClass('requiredInputError'); } else if (item == 'message') { form.children('textarea[name="message"]').addClass('requiredInputError'); } else { form.children('input[name="' + item + '"]').addClass('requiredInputError'); } }); } else { alert(json.msg); } } } }); }); |
Файл make.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
<?php $name = $_REQUEST['name']; $email = $_REQUEST['email']; $phone = $_REQUEST['phone']; $message = $_REQUEST['message']; $agree = isset($_REQUEST['agree']); $errors = false; $requiredFields = ['name', 'email', 'phone', 'agree', 'message']; $errorFields = []; // проверяем обязательные поля foreach($requiredFields as $field){ if (!$_REQUEST[$field]){ array_push($errorFields, $field); $errors = true; } } if (!$errors) : $subjectuser = "Сообщение"; $headersuser = "From: Сообщение\r\n"; $headersuser .= "Reply-To: ". strip_tags($name) . "\r\n"; $headersuser .= "MIME-Version: 1.0\r\n"; $headersuser .= "Content-Type: text/html;charset=utf-8 \r\n"; $my_message = "<h1>ТЕМА</h1><br/>"; $my_message .= "Имя: {$name}<br/>"; if ($phone){ $my_message .= "Телефон: {$phone}<br />"; } if ($email){ $my_message .= "E-mail: {$email}<br />"; } if ($message){ $my_message .= "Комментарий: <br>" . $message . "<hr/>"; } $my_message .= "Время заказа: " . date('H:i:s d.m.Y'); require_once($_SERVER['DOCUMENT_ROOT'] . '/include/libs/PHPMailer/class.phpmailer.php'); //Подключаем PHPMailer $mail = new PHPMailer(true); //New instance, with exceptions enabled $mail->CharSet = "UTF-8"; $mail->IsSMTP(); // telling the class to use SMTP $mail->Host = "smtp.yandex.ru"; // SMTP server $mail->SMTPDebug = 0; // enables SMTP debug information (for testing) $mail->SMTPAuth = true; // enable SMTP authentication $mail->Port = 465; // set the SMTP port for the GMAIL server $mail->SMTPSecure = 'ssl'; // Secure SMTP $mail->Username = 'from@matveevs,ru'; // SMTP account username $mail->Password = "fromPassword"; // SMTP account password $mail->SetFrom('from@matveevs,ru', 'site.ru'); $mail->AddReplyTo('from@matveevs,ru','site.ru'); $mail->Subject = "Сообщение с сайта site.ru"; $mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test $mail->MsgHTML($my_message); $address = 'to@matveevs.ru'; $mail->AddAddress($address, "User"); $mail->CharSet="UTF-8"; $mail->IsHTML(true); // send as HTML if(!$mail->Send()) : $res = Array( "result" => false, "msg" => "Ошибка отправления" ); else: $res = Array( "result" => true, "msg" => "Спасибо! Ваша заявка отправлена" ); require $_SERVER["DOCUMENT_ROOT"] . '/addToBitrix.php'; endif; else: $res = Array( "result" => false, "msg" => "Ошибка: заполните все поля формы", "errors" => $errorFields ); endif; echo json_encode($res, JSON_UNESCAPED_UNICODE); |
addToBitrix.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php require $_SERVER["DOCUMENT_ROOT"] . '/bitrix/modules/main/include/prolog_before.php'; CModule::IncludeModule("catalog"); $el = new CIBlockElement; $PROP = array( "NAME" => $name, "PHONE" => $phone, "EMAIL" => $email, "MESSAGE" => $message ); $arFields = array( "IBLOCK_ID" => 10, "IBLOCK_SECTION_ID" => false, "NAME" => $name, "PROPERTY_VALUES" => $PROP, "ACTIVE" => "Y", ); $el->Add($arFields); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// https://modx.ru/vopros-otvet/info/1890/ // https://docs.modx.pro/components/minishop2/development/service/connection // https://docs.modx.pro/components/minishop2/development/service/basket var CustomBasket = { add : function (id, size){ $.ajax({ type: "POST", url: "/assets/components/minishop2/action.php", data: "id=" + id + "&count=1&options[size]=" + size + "&ms2_action=cart/add&ctx=web", success: function(msg){ json = $.parseJSON(msg); CustomBasket.countMobileBasket(json.data.total_count); console.log("Добавлен товар: " + id + " " + size); } }); }, countMobileBasket : function(countElement){ $('#msMiniCartMobile a.quickview.link_order').html(countElement); } }; |
Событие на клик для мобильного устройства
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
var activeElement = null; var isMobileMode = false; var MobileClick = false; /** * mobile detected function * @return Boolean isMobile/true||isMobile/false */ window.isMobileOrTablet = function() { var check = false; (function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))check = true})(navigator.userAgent||navigator.vendor||window.opera); return check; } /** * If mobile Device var isMobile set True */ if(isMobileOrTablet()) { console.log('Вы зашли с мобильного устройства'); isMobileMode = true; } else { console.log('Вы с desktop'); } console.log(isMobileMode + ' моб'); if (isMobileMode){ $('button.btn.js_add_swimwear').click(function(event){ if (!MobileClick){ event.preventDefault(); if ($('#' + activeElement + ' .size-list .size-item').hasClass('active')){ if (!$('.mobile_popup').hasClass('active')){ $('.mobile_popup').addClass('active').show(); $('.t_popup').hide(); $('#' + url_id_target).hide(); id = $('#' + activeElement + ' form.form-horizontal.ms2_form input[name="id"]').val(); size = $('#' + activeElement + ' form.form-horizontal.ms2_form input[name="options[size]"]').val(); CustomBasket.add(id, size); console.log(id + ' ' + size); } } console.log('mobile click!'); } }); console.log('mobile'); } |
Для определения с мобильного устройства пользователь зашел на сайт или нет можно следующим говноКодом
1 2 3 4 5 |
window.isMobileOrTablet = function() { var check = false; (function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))check = true})(navigator.userAgent||navigator.vendor||window.opera); return check; } |
Проверить
1 2 3 4 5 |
if(isMobileOrTablet()) { console.log('Вы зашли с мобильного устройства'); } else { console.log('Вы с desktop'); } |
В firefox с выходом версии 59, перестало срабатывать javascript/jQuery событие click в плагине bxslider? Отрываем jquery.bxslider.js находим строку ~#1111
1 2 3 4 |
if (slider.viewport.get(0).setPointerCapture) { slider.pointerId = orig.pointerId; slider.viewport.get(0).setPointerCapture(slider.pointerId); } |
Меняем на
1 2 3 4 5 6 |
if (slider.viewport.get(0).setPointerCapture) { slider.pointerId = orig.pointerId; if(slider.pointerId === 1){ slider.viewport.get(0).setPointerCapture(slider.pointerId); } } |
Или Скачать исправленную версию. p.s.: если сделать событие mousedown то будет работать) но лучше lib’у править Проблема на GitHub.
Iphone/ios click event Событие клик на iphone не работает?
1 2 3 4 |
$(document).on('click', '.p_cab_mob', function() { $(this).toggleClass('open_h5'); $(this).parent().parent().toggleClass('open'); }); |
Есть 2 варианта решения этой проблемы #1 С добавление event touchstart
1 2 3 4 |
$(document).on('click touchstart', '.p_cab_mob h5', function() { $(this).toggleClass('open_h5'); $(this).parent().parent().toggleClass('open'); }); |
#2 Событие click
1 2 3 4 |
$('.p_cab_mob h5').click(function(){ $(this).toggleClass('open_h5'); $(this).parent().parent().toggleClass('open'); }); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
function checkFlash() { var flashinstalled = false; if (navigator.plugins) { if (navigator.plugins["Shockwave Flash"]) { flashinstalled = true; } else if (navigator.plugins["Shockwave Flash 2.0"]) { flashinstalled = true; } } else if (navigator.mimeTypes) { var x = navigator.mimeTypes['application/x-shockwave-flash']; if (x && x.enabledPlugin) { flashinstalled = true; } } else { // на всякий случай возвращаем true в случае некоторых экзотических браузеров flashinstalled = true; } return flashinstalled; } |
Флеш/flash для браузера клиента, если не разрешен то функция вернет false, если разрешен вернет true Пример
1 2 3 4 5 6 7 8 9 10 11 |
brow = false; if (navigator.userAgent.match(/Chrome/i) || navigator.userAgent.match(/Safari/i)){ brow = true; } if (document.location.pathname == "/video" && !checkFlash() && brow){ $('#swf_lessons').html('<object width="550" height="400">\ <param name="movie" value="/lessons/my.swf">\ <embed src="/lessons/my.swf" width="550" height="400">\ </embed>\ </object>'); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
/** * Работа с Google Ecommerce */ var GoogleAnalytics = { /** * Детальная страница * @param integer id идентификатор товара * @param string name Название товара * @param string category Категория товара * @return null Отправка данных в GA */ viewDetailItem: function(id, name, category){ ga('ec:addProduct', { 'id': id, 'name': name, 'category': category }); ga('ec:setAction', 'detail'); ga('send', 'pageview'); // Отправляем данные }, /** * Добавление/удаление товара в корзине * @param integer id id товара * @param string name наименование товара * @param string category категория товара * @param integer price цена товара * @param integer type тип событие 0-добавление, 1 удаление */ EventItemBasket: function(id, name, category, price, type){ type_event = type == 0 ? 'add' : 'remove'; ga('ec:addProduct', { 'id': id, 'name': name, 'category': category, 'price': price, 'quantity': 1 }); ga('ec:setAction', type_event); event = type == 0 ? "Добавил в корзину" : "Удалил товар из корзины"; ga('send', 'event', 'Корзина', event, 'Клик в карточке товара'); // Send data using an event. }, /** * Отправка содержимого корзины * @param array arr json Массив * @param integer total_price финальная стоимость заказа * @param string id basket session * @return NULL отправляем все это в гугл */ eventBasketSend: function(arr, total_price, id){ items = JSON.parse(arr); items.forEach(function(key, value){ element_id = key.elem_id; quantity = key.quantity; price = key.price; title = key.site_title; ga('ec:addProduct', { 'id': element_id, 'name': title, 'price': price, 'quantity': quantity }); }); ga('ec:setAction', 'purchase', { 'id': id, 'affiliation': 'site.ru', 'revenue': total_price }); ga('send', 'pageview'); } }; |
Документация Код гугл аналитики вставить перед </head>
1 2 3 4 5 6 7 8 9 10 11 12 |
<!-- Google Analytics --> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-XXXXXXX-1', 'site.ru'); ga('send', 'pageview'); ga('require', 'ec'); </script> <!-- End Google Analytics --> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
$('#t_popup').scroll(function(){ pop_img_cont = $('#popup_static').height(); fix = $('.popup_fixed'); elem = Math.abs($(".c-popup").offset().top) + 590; top1 = pop_img_cont - 590; if (elem >= pop_img_cont){ console.log('trigger'); fix.css({position : "relative", top : top1}); } else { fix.css({position : "fixed", top : "unset"}); console.log('wait'); } }); |
scroll modal window скроль модального окна
Исследование элемента: Выбрать элемент(исследовать), и ввести в консоли
1 |
$._data(($0), 'events') |
и смотреть handler(нажать 2 раза) Редактирование страницы «на живую»
1 |
document.body.contentEditable=true |
Вывод всех свойств элемента
1 2 3 4 5 |
dir($('selector')) или $('selector') |
Источник: https://habrahabr.ru/company/ruvds/blog/316132/ Google Chrome