Обучаю битриксу программистов, интеграторов. Подробнee ⇒

jquery, javascript сниппеты



if(typeof a === 'undefined'){

}

window.location = '404.html';
на кейап с задержкой реагируем, чтобы когда закончил печатать сделать
$('#myfield').on('keyup',function(){   
   var val = $('#myfield').val();
   var interval = setInterval(
        function(){
            if($('#myfield).val() == val){
                //Что-нибудь делаем
            }                    
            clearInterval(interval);
        }, 
    700);
});
проверка email на валидность
function CheckEmail(email){
   var ret = false;
   var pattern = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|.(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
   if((email != '') && pattern.test(email)){
      ret = true;            
   }
   return ret;
}

ajax
let dataRequest = {
   town : currentTown,
   street: currentStreet,
   house: currentHouse
}            
$.ajax({
     url: "ajax.php",
     data: dataRequest,
     type: "GET",
     dataType: "json"

}).done(function(data) {
   //что-нибудь делаем              
     
}).fail(function(data){
   console.log(data);
});
json
let result = {}; //как-то заполняем
$("#result").val(JSON.stringify(result)); //кодирует
result = JSON.parse($("#result").val()); //декодирует

checked,selected
$('#elemId').prop('checked'); //true or false
$('#optionId').prop('selected',true); //ставим selected у option select
let option = $('select#elemId option:selected'); //получим выбранный option у select 

для своего поля кастомного типа, основанного на datetime, template.php
плагин https://xdsoft.net/jqplugins/datetimepicker/
//php
$APPLICATION->AddHeadScript('/local/templates/.default/js/jquery-3.6.0.min.js'); 
$APPLICATION->AddHeadScript('/local/templates/.default/js/jquery.datetimepicker.full.min.js');
$APPLICATION->SetAdditionalCSS('/local/templates/.default/css/jquery.datetimepicker.min.css');
//js
$(document).ready(function(){
   $.datetimepicker.setLocale('ru');
   $('#<?=$name?>_datetimepicker').datetimepicker({
      
      minDate:0,//or 1986/12/08
      timepicker:true,
      format:"d.m.Y H:i",
      hours12: false,                  
      inline:true,
      allowTimes:[
             '08:00', '08:30', '09:00', '09:30', '10:00', '10:30', '11:00', '11:30', 
           '12:00', '12:30', '13:00', '13:30', '14:00', '14:30', '15:00', '15:30',
           '16:00', '16:30', '17:00', '17:30', '18:00', '18:30' , '19:00' , '19:30',
           '20:00', '20:30', '21:00', '21:30', '22:00', '22:30' 
         ]
      ,
      onSelectDate:function(ct,$i){                     
        BX.fireEvent(BX('<?=$name?>_datetimepicker'),'change');
        BX.fireEvent(BX('<?=$name?>_datetimepicker'),'oninput');                    
      },
      onSelectTime:function(ct,$i){                  
        BX.fireEvent(BX('<?=$name?>_datetimepicker'),'change');
        BX.fireEvent(BX('<?=$name?>_datetimepicker'),'oninput');                    
      },

   });
   $('#<?=$name?>_datetimepicker').change(function(){
      
      let day =$('#<?=$name?>_datetimepicker').val();
      day =  day.split(" ")[0];               
      dataRequest = {
         get_connection_to_day: day,
         id: '<?=$arParams["arUserField"]["ENTITY_VALUE_ID"]?>'                  
      };
      $('#mes_<?=$name?>').html();
      $.ajax({
           url: "<?=$this->GetFolder()?>/ajax.php",
           data: dataRequest,
           type: "GET",
           dataType: "json"

      }).done(function(data) {
         let text = '';
         if(data>0){
            $('#mes_<?=$name?>').html('Запланировано '+data+' подкл. на '+day);   
         }
         else{
            $('#mes_<?=$name?>').html('НЕТ других запланированных подключений на '+day);      
         }
      });
   });
});
плавная прокрутка до элемента
вариант 1
$(document).ready(function(){
   $('a[href=#rec294391208]').on('click', function(e){
      e.preventDefault();
        $('html,body').stop().animate({ scrollTop: $('#rec294391208').offset().top }, 500);    
   });
});
вариант 2

$(document).ready(function(){   
   $(document).on("click", ".page-wrap .page a", function() {
      window.scrollTo({ top: 0, behavior: 'smooth' })
   });
});
изменить адрес js и отпправить в браузер в историю
history.pushState({ 'page_id': page_id++}, title, curLoc);
NavigationCache[window.location.pathname] = $('main').html();

при прокрутке фиксируем какой-нить элемент
window.addEventListener("pageshow", function () {    //pageshow круче для мобилки чем load
   if($('.expande-collapse').length==1){ //если такой элемент 1
        window.addEventListener("scroll", function () {
            $('.expande-collapse').each(function(ind,e){

                let coords = e.getBoundingClientRect();
                let top = coords.top + window.scrollY;
                
                if(!$(e).hasClass('fixed')) {
                    if (window.scrollY > top) {
                        $(e).addClass("fixed");
                        $(e).data('top', top);
                    }
                }
                else{
                    if(window.scrollY < $(e).data('top')){
                        $(e).removeClass("fixed");
                    }
                }
            });
        });
    }
});
чиним gtag is not defined
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
 gtag('event', 'Submit', {
 'event_category' : 'Form',
 'event_label' : 'MyEvent'
});

по клику ссылки получить родителя и там че-нить кликнуть
$(document).ready(function(){   
   $('.video__info-link').on("click",function(e){
      e.preventDefault();       
      $(this).parents('.video').first().find(".vjs-big-play-button").first().trigger("click");
   });
});
скопировать по клику в буфер обмена
html
<a href="#" data-id='123123'>Copy to clipboard</a>
js
$('.copySerialNumber').on('click',function(e){    e.preventDefault();
    navigator.clipboard.writeText($(this).data('id'))
        .then(() => console.log(""))
        .catch(err => console.error(err))
});
Добавить onclick на все tel ссылки
$("a[href^='tel']").on("click",function(){
    _gap.push(['_trackEvent', 'Mobile', 'Click to Call']); 
});
Сконвертировать SVG polygon в path
открыть свг, в консоли выполнить
var polys = document.querySelectorAll('polygon,polyline'); [].forEach.call(polys,convertPolyToPath);

 function convertPolyToPath(poly){
   var svgNS = poly.ownerSVGElement.namespaceURI;
   var path = document.createElementNS(svgNS,'path');
   var pathdata = 'M '+poly.getAttribute('points');
   if (poly.tagName=='polygon') pathdata+='z';
   path.setAttribute('d',pathdata);
   poly.getAttributeNames().forEach(function(name){
     if(name !== 'points')
       path.setAttribute(name, poly.getAttribute(name))
   })
   poly.parentNode.replaceChild(path,poly);
 }

Методы массивов Javascript
let arr,arr1,arr2;
.filter фильтрует элементы массива
arr = [3,2,3,4,3,5];
arr1 = arr.filter((num) => num > 2); 
arr2 = arr.filter(function(num){
   //тут может быть сложная логика 
   return num>2;
}); 

console.log(arr);//[3,2,3,4,3,5] arr не изменился
console.log(arr1);//[3, 3, 4, 3, 5]
console.log(arr2); //[3, 3, 4, 3, 5]

.find ищет элемент массива
arr = [3,2,3,4,3,5];
arr1 = arr.find((num) => num > 3); 
console.log(arr);//[3,2,3,4,3,5] arr не изменился
console.log(arr1);//4

.findIndex ищет индекс элемент массива
arr = [3,2,3,4,3,5];
arr1 = arr.findIndex((num) => num > 3); 
console.log(arr);//[3,2,3,4,3,5] arr не изменился
console.log(arr1);//4

.some есть ли хотя бы 1 элемент для условия
arr = [3,2,3,4,3,5];
arr1 = arr.some((num) => num % 2 === 0); 
console.log(arr);//[3,2,3,4,3,5] arr не изменился
console.log(arr1);//true (а для пустого массива метод возвращает false при любом условии )

.every удовлетворяют ли все элементы условию
arr = [3,2,3,4,3,5];
arr1 = arr.every((element, index, array) => element >= 4); //false

.reverse переворачивает массив
arr = [3,2,3,4,3,5];
arr1 = arr.reverse(); 
console.log(arr);// [5, 3, 4, 3, 2, 3] arr изменился
console.log(arr1);// [5, 3, 4, 3, 2, 3]
.shift удаляет 1й элемент массива
arr = [3,2,3,4,3,5];
arr1 = arr.shift();
console.log(arr);//[2, 3, 4, 3, 5] arr изменился
console.log(arr1);//3 - удаленный элемент
.pop удаляет последний элемент массива
arr = [3,2,3,4,3,5];
arr1 = arr.pop();
console.log(arr);// [3, 2, 3, 4, 3] arr изменился
console.log(arr1);// 5 - новая длина массива

.unshift добавляет в начало массива новые элементы
arr = [3,2,3,4,3,5];
arr1 = arr.unshift(4,6);
console.log(arr);//[4, 6, 3, 2, 3, 4, 3, 5] arr изменился
console.log(arr1);//8 - новая длина массива

.push добавляет в конец массива новые элементы
arr = [3,2,3,4,3,5];
arr1 = arr.push(2,7);
console.log(arr);//[3, 2, 3, 4, 3, 5, 2, 7] arr изменился
console.log(arr1);//8 - новая длина массива
.map модифицирует элементы массива
arr = [3,2,3,4,3,5];
arr1 = arr.map(function (num) {return num*2});
console.log(arr);// [3, 2, 3, 4, 3, 5] arr не изменился
console.log(arr1);// [6, 4, 6, 8, 6, 10]

Если блог был полезным, можете угостить меня "чашечкой кофе" :)

Сбер по номеру телефона +7 (953) 585-13-09 Вероника.
Спасибо!