Не работает код на странице contact Drupal 8

Главные вкладки

Аватар пользователя Babich Babich 17 июля 2018 в 16:20

Всем здравствуйте, заранее благодарю за помощь.

Сделал код, он должен стилизовать checkbox.

Создал файл Customjs.js

jQuery(document).ready(function(){

/*************** Checkbox script ***************/
jQuery(document).bind('ready ajaxComplete', function() {
var inputs = document.getElementsByTagName('input');
for (a = 0; a < inputs.length; a++) {
if (inputs[a].type == "checkbox") {
var id = inputs[a].getAttribute("id");
if (id==null){
id=  "checkbox" +a;
}
inputs[a].setAttribute("id",id);
var container = document.createElement('div');
container.setAttribute("class", "bc_checkbox");
var label = document.createElement('label');
label.setAttribute("for", id);
jQuery(inputs[a]).wrap(container).after(label);
}
}
});
});

Прописал его в файл themename.libraries.yml

global-styling-and-scripts:
 version: VERSION
 css:
  theme:
   css/bootstrap.css: {}
   css/style.css: {}
 dependencies:
  - core/jquery
  - core/jquery.ui.effects.core
  - core/jquery.ui.effects.bounce
  - core/jquery.ui.effects.slide
  - core/jquery.ui.effects.fade
  - core/jquery.ui.effects.drop
  - core/jquery.ui.effects.blind
  - core/jquery.ui.effects.puff
  - core/jquery.ui.effects.pulsate
  - core/jquery.ui.effects.highlight
  - core/jquery.ui.effects.scale
  - core/jquery.ui.effects.shake
  - core/jquery.ui.effects.size
  - core/jquery.ui.effects.transfer
  - core/jquery.ui.effects.clip
 js:
  js/totop.js: {}
  js/bootstrap.min.js: {}
  js/Customjs.js: {}
  js/html5shiv.js: {}
  js/respond.min.js: {}

В модальном окне checkbox стилизуется, а на странице модуля contact не хочет.

Лучший ответ

Аватар пользователя ivnish ivnish 17 июля 2018 в 16:47

А зачем стилизовать checkbox через JS, когда проще сразу использовать CSS?

Комментарии

Аватар пользователя Babich Babich 17 июля 2018 в 16:54

Уже работа проделана, делал с помощью js (добавлял div checkbox), потом стилизовал через css. Только сейчас увидел, что на странице формы не работает. К тому же хочется понять почему не работает. Если не решу сделаю на чистом css.

Аватар пользователя Babich Babich 17 июля 2018 в 19:04

Ошибка в консоли есть, но я думаю, она по причине использования на локальном хостинге версии php 7.1. На drupalhosting такой проблемы нет.

Uncaught Error: Quick Edit could not associate the rendered entity field markup (with [data-quickedit-field-id="node/2/body/ru/full"]) with the corresponding rendered entity markup: no parent DOM node found with [data-quickedit-entity-id="node/2"]. This is typically caused by the theme's template for this entity type forgetting to print the attributes.
    at processField (quickedit.js?v=8.5.5:165)
    at HTMLDivElement.<anonymous> (quickedit.js?v=8.5.5:37)
    at Function.each (jquery.min.js?v=3.2.1:2)
    at r.fn.init.each (jquery.min.js?v=3.2.1:2)
    at Object.attach (quickedit.js?v=8.5.5:36)
    at drupal.js?v=8.5.5:25
    at Array.forEach (<anonymous>)
    at Object.Drupal.attachBehaviors (drupal.js?v=8.5.5:22)
    at drupal.init.js?v=8.5.5:16
    at HTMLDocument.t (ready.min.js?v=1.0.8:4)
Аватар пользователя Olegars Olegars 17 июля 2018 в 19:39

php и консоль никак несвязаны
это раз
quickedit.js jquery.min.js и т.д это точно не php
это два
а причина вот "no parent DOM node found with [data-quickedit-entity-id="node/2"]"

Аватар пользователя Babich Babich 17 июля 2018 в 21:04

Вы правы. Я просто посмотрел на рабочий сайт, ошибки в консоли там не оказалось. Всё по причине того, что страница выведена через модуль views. А на обычной странице ошибка есть. Я так понимаю ошибка кроется в теме, но не могу понять где. Нашёл похожую ситуацию, но не знаю, она ли это и как её решить. https://www.drupal.org/project/drupal/issues/2978799

Аватар пользователя Babich Babich 17 июля 2018 в 21:17

И опять же проблема возникает только под админом (не дает быстро редактировать ноды). Под обычным юзером все нормально (консоль чистая). А стили к чекбоксу всё равно работать не хотят.

Аватар пользователя Babich Babich 17 июля 2018 в 22:52

Модуль Quick Edit я пока отключил, чтобы не было ошибок в консоли. Теперь она чистая и скрипт подгружается, а чекбоксу div всё равно не добавляется.

Аватар пользователя Babich Babich 17 июля 2018 в 23:46

Странно как-то . Вот сейчас под админом показался и то когда по кнопке в новой вкладке открыл форму. Потом после перезагрузки страницы снова нет. А под обычным юзером вообще не показывает.

Аватар пользователя gun_dose gun_dose 18 июля 2018 в 6:56

Вы используете document.ready вместо бихэворов, потому и не срабатывает. 99%, что у вас включен биг пайп, и во время события ready формы ещё нет на странице.

Аватар пользователя Babich Babich 18 июля 2018 в 9:17

Вы правы. биг пайп включен. А куда надо добавить Drupal.behaviors? Что убрать? вот весь код Customjs.js

jQuery(document).ready(function(){

/*************** Checkbox script ***************/
jQuery(document).bind('ready ajaxComplete', function() {
var inputs = document.getElementsByTagName('input');
for (a = 0; a < inputs.length; a++) {
if (inputs[a].type == "checkbox") {
var id = inputs[a].getAttribute("id");
if (id==null){
id=  "checkbox" +a;
}
inputs[a].setAttribute("id",id);
var container = document.createElement('div');
container.setAttribute("class", "bc_checkbox");
var label = document.createElement('label');
label.setAttribute("for", id);
jQuery(inputs[a]).wrap(container).after(label);
}
}
});

/*************** Radiobutton script ***************/
jQuery(document).bind('ready ajaxComplete', function() {
var inputs = document.getElementsByTagName('input');
for (a = 0; a < inputs.length; a++) {
if (inputs[a].type == "radio") {
var id = inputs[a].getAttribute("id");
if (id==null){
 id=  "radio" +a;
}
inputs[a].setAttribute("id",id);
var container = document.createElement('div');
container.setAttribute("class", "bc_radio");
var label = document.createElement('label');
label.setAttribute("for", id);
jQuery(inputs[a]).wrap(container).after(label);
}
}
});

/*************** Staticfooter script ***************/
var window_height =  Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
var body_height = jQuery(document.body).height();
var content = jQuery("#bc_content_and_sidebar_container");
if(body_height < window_height){
differ = (window_height - body_height);
content_height = content.height() + differ;
jQuery("#bc_content_and_sidebar_container").css("min-height", content_height+"px");
}

/* Slideshow Function Call */

if(jQuery('#bc_slideshow_inner').length){
jQuery('#bc_slideshow_inner').TTSlider({
slideShowSpeed:2000, begintime:1000,cssPrefix: 'bc_'
});
}

/*************** Hamburgermenu slideleft script ***************/
jQuery('#nav-expander').on('click',function(e){
e.preventDefault();
jQuery('body').toggleClass('nav-expanded');
});

/*************** Menu click script ***************/
jQuery('ul.bc_menu_items.nav li [data-toggle=dropdown]').on('click', function() {
var window_width =  Math.max(document.documentElement.clientWidth, window.innerWidth || 0)
if(window_width > 1025 && jQuery(this).attr('href')){
window.location.href = jQuery(this).attr('href');
}
else{
if(jQuery(this).parent().hasClass('open')){
location.assign(jQuery(this).attr('href'));
}
}
});

/*************** Sidebarmenu click script ***************/
jQuery('ul.bc_vmenu_items.nav li [data-toggle=dropdown]').on('click', function() {
var window_width =  Math.max(document.documentElement.clientWidth, window.innerWidth || 0)
if(window_width > 1025 && jQuery(this).attr('href')){
window.location.href = jQuery(this).attr('href');
}
else{
if(jQuery(this).parent().hasClass('open')){
location.assign(jQuery(this).attr('href'));
}
}
});

/*************** Tab menu click script ***************/
jQuery('.bc_menu_items ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {
var window_width =  Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
if(window_width < 1025){
event.preventDefault();
event.stopPropagation();
jQuery(this).parent().siblings().removeClass('open');
jQuery(this).parent().toggleClass(function() {
if (jQuery(this).is(".open") ) {
window.location.href = jQuery(this).children("[data-toggle=dropdown]").attr('href');
return "";
} else {
return "open";
}
});
}
});

/*************** Tab-Sidebarmenu script ***************/
jQuery('.bc_vmenu_items ul [data-toggle=dropdown]').on('click', function(event) {
var window_width =  Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
if(window_width < 1025){
event.preventDefault();
event.stopPropagation();
jQuery(this).parent().siblings().removeClass('open');
jQuery(this).parent().toggleClass(function() {
if (jQuery(this).is(".open") ) {
window.location.href = jQuery(this).children("[data-toggle=dropdown]").attr('href');
return "";
} else {
return "open";
}
});
}
});

/*************** Sticky menu script ***************/
var menuheight = jQuery('nav.navbar').height();
var menutop = jQuery('#bc_menu').offset().top;
 jQuery(document).scroll(function () {
var scrollTop = jQuery(this).scrollTop();
var menuOffset = menutop - menuheight;
if(menuOffset < 0)
{
menuOffset = 0;
}
if (scrollTop > menutop)
{
jQuery('#bc_menu').addClass('navbar-fixed-top');
}
else if (scrollTop <= menuOffset)
{
jQuery('#bc_menu').removeClass('navbar-fixed-top');
}
});
WebFontConfig = {
google: { families: [ 'Open+Sans:700','Open+Sans','Varela+Round','Varela+Round:700'] }
};
(function() {
var wf = document.createElement('script');
wf.src = ('https:' == document.location.protocol ? 'https' : 'http') + '://ajax.googleapis.com/ajax/libs/webfont/1.0.31/webfont.js';
wf.type = 'text/javascript';
wf.async = 'true';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(wf, s);
})();
});

Аватар пользователя Babich Babich 18 июля 2018 в 10:04

Вот такой код добавил в Customjs.js

(function($){
 Drupal.behaviors.my_behavior = {
  attach: function(context, settings) {
jQuery(document).ready(function(){

/*************** Checkbox script ***************/
jQuery(document).bind('ready ajaxComplete', function() {
var inputs = document.getElementsByTagName('input');
for (a = 0; a < inputs.length; a++) {
if (inputs[a].type == "checkbox") {
var id = inputs[a].getAttribute("id");
if (id==null){
id=  "checkbox" +a;
}
inputs[a].setAttribute("id",id);
var container = document.createElement('div');
container.setAttribute("class", "bc_checkbox");
var label = document.createElement('label');
label.setAttribute("for", id);
jQuery(inputs[a]).wrap(container).after(label);
}
}
});

/*************** Radiobutton script ***************/
jQuery(document).bind('ready ajaxComplete', function() {
var inputs = document.getElementsByTagName('input');
for (a = 0; a < inputs.length; a++) {
if (inputs[a].type == "radio") {
var id = inputs[a].getAttribute("id");
if (id==null){
 id=  "radio" +a;
}
inputs[a].setAttribute("id",id);
var container = document.createElement('div');
container.setAttribute("class", "bc_radio");
var label = document.createElement('label');
label.setAttribute("for", id);
jQuery(inputs[a]).wrap(container).after(label);
}
}
});

/*************** Staticfooter script ***************/
var window_height =  Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
var body_height = jQuery(document.body).height();
var content = jQuery("#bc_content_and_sidebar_container");
if(body_height < window_height){
differ = (window_height - body_height);
content_height = content.height() + differ;
jQuery("#bc_content_and_sidebar_container").css("min-height", content_height+"px");
}

/* Slideshow Function Call */

if(jQuery('#bc_slideshow_inner').length){
jQuery('#bc_slideshow_inner').TTSlider({
slideShowSpeed:2000, begintime:1000,cssPrefix: 'bc_'
});
}

/*************** Hamburgermenu slideleft script ***************/
jQuery('#nav-expander').on('click',function(e){
e.preventDefault();
jQuery('body').toggleClass('nav-expanded');
});

/*************** Menu click script ***************/
jQuery('ul.bc_menu_items.nav li [data-toggle=dropdown]').on('click', function() {
var window_width =  Math.max(document.documentElement.clientWidth, window.innerWidth || 0)
if(window_width > 1025 && jQuery(this).attr('href')){
window.location.href = jQuery(this).attr('href');
}
else{
if(jQuery(this).parent().hasClass('open')){
location.assign(jQuery(this).attr('href'));
}
}
});

/*************** Sidebarmenu click script ***************/
jQuery('ul.bc_vmenu_items.nav li [data-toggle=dropdown]').on('click', function() {
var window_width =  Math.max(document.documentElement.clientWidth, window.innerWidth || 0)
if(window_width > 1025 && jQuery(this).attr('href')){
window.location.href = jQuery(this).attr('href');
}
else{
if(jQuery(this).parent().hasClass('open')){
location.assign(jQuery(this).attr('href'));
}
}
});

/*************** Tab menu click script ***************/
jQuery('.bc_menu_items ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {
var window_width =  Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
if(window_width < 1025){
event.preventDefault();
event.stopPropagation();
jQuery(this).parent().siblings().removeClass('open');
jQuery(this).parent().toggleClass(function() {
if (jQuery(this).is(".open") ) {
window.location.href = jQuery(this).children("[data-toggle=dropdown]").attr('href');
return "";
} else {
return "open";
}
});
}
});

/*************** Tab-Sidebarmenu script ***************/
jQuery('.bc_vmenu_items ul [data-toggle=dropdown]').on('click', function(event) {
var window_width =  Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
if(window_width < 1025){
event.preventDefault();
event.stopPropagation();
jQuery(this).parent().siblings().removeClass('open');
jQuery(this).parent().toggleClass(function() {
if (jQuery(this).is(".open") ) {
window.location.href = jQuery(this).children("[data-toggle=dropdown]").attr('href');
return "";
} else {
return "open";
}
});
}
});

/*************** Sticky menu script ***************/
var menuheight = jQuery('nav.navbar').height();
var menutop = jQuery('#bc_menu').offset().top;
 jQuery(document).scroll(function () {
var scrollTop = jQuery(this).scrollTop();
var menuOffset = menutop - menuheight;
if(menuOffset < 0)
{
menuOffset = 0;
}
if (scrollTop > menutop)
{
jQuery('#bc_menu').addClass('navbar-fixed-top');
}
else if (scrollTop <= menuOffset)
{
jQuery('#bc_menu').removeClass('navbar-fixed-top');
}
});
WebFontConfig = {
google: { families: [ 'Open+Sans:700','Open+Sans','Varela+Round','Varela+Round:700'] }
};
(function() {
var wf = document.createElement('script');
wf.src = ('https:' == document.location.protocol ? 'https' : 'http') + '://ajax.googleapis.com/ajax/libs/webfont/1.0.31/webfont.js';
wf.type = 'text/javascript';
wf.async = 'true';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(wf, s);
})();
});  
  }}
})(jQuery);

Теперь под админом, я так понимаю срабатывает несколько раз (в модальном окне). На странице contact не срабатывает. А под обычным юзером в модальном окне показывает, а на странице contact все равно нет.

Аватар пользователя gun_dose gun_dose 18 июля 2018 в 10:24

1. jQuery теперь можно смело заменять на доллар для краткости.
2. Конструкции типа jQuery(document).bind() замените на
jQuery(document).once('my_behavior').bind()

Функция once означает, что обработчик должен выполниться только один раз.

Аватар пользователя Babich Babich 18 июля 2018 в 10:42

Фрагмент кода

/*************** Checkbox script ***************/
jQuery(document).once('my_behavior').bind()('ready ajaxComplete', function() {
var inputs = document.getElementsByTagName('input');
for (a = 0; a < inputs.length; a++) {
if (inputs[a].type == "checkbox") {
var id = inputs[a].getAttribute("id");
if (id==null){
id=  "checkbox" +a;
}
inputs[a].setAttribute("id",id);
var container = document.createElement('div');
container.setAttribute("class", "bc_checkbox");
var label = document.createElement('label');
label.setAttribute("for", id);
jQuery(inputs[a]).wrap(container).after(label);
}
}
});

Ошибка в консоли

jquery.min.js?v=3.2.1:2 jQuery.Deferred exception: jQuery(...).once(...).bind(...) is not a function TypeError: jQuery(...).once(...).bind(...) is not a function
    at HTMLDocument.<anonymous> (http://akvafitness/themes/akvafitness/js/Customjs.js?v=8.5.5:7:44)
    at j (http://akvafitness/core/assets/vendor/jquery/jquery.min.js?v=3.2.1:2:29999)
    at k (http://akvafitness/core/assets/vendor/jquery/jquery.min.js?v=3.2.1:2:30313) undefined
r.Deferred.exceptionHook @ jquery.min.js?v=3.2.1:2
jquery.min.js?v=3.2.1:2 Uncaught TypeError: jQuery(...).once(...).bind(...) is not a function
    at HTMLDocument.<anonymous> (Customjs.js?v=8.5.5:7)
    at j (jquery.min.js?v=3.2.1:2)
    at k (jquery.min.js?v=3.2.1:2)
jquery.min.js?v=3.2.1:4 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
send @ jquery.min.js?v=3.2.1:4
2jquery.min.js?v=3.2.1:2 jQuery.Deferred exception: jQuery(...).once(...).bind(...) is not a function TypeError: jQuery(...).once(...).bind(...) is not a function
    at HTMLDocument.<anonymous> (http://akvafitness/themes/akvafitness/js/Customjs.js?v=8.5.5:7:44)
    at j (http://akvafitness/core/assets/vendor/jquery/jquery.min.js?v=3.2.1:2:29999)
    at k (http://akvafitness/core/assets/vendor/jquery/jquery.min.js?v=3.2.1:2:30313) undefined
r.Deferred.exceptionHook @ jquery.min.js?v=3.2.1:2
2jquery.min.js?v=3.2.1:2 Uncaught TypeError: jQuery(...).once(...).bind(...) is not a function
    at HTMLDocument.<anonymous> (Customjs.js?v=8.5.5:7)
    at j (jquery.min.js?v=3.2.1:2)
    at k (jquery.min.js?v=3.2.1:2)