forked from FreelancerLifeStyle/dynamic_adapt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
174 lines (161 loc) · 5.7 KB
/
script.js
File metadata and controls
174 lines (161 loc) · 5.7 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
// Dynamic Adapt v.1
// HTML data-da="where(uniq class name),position(digi),when(breakpoint)"
// e.x. data-da="item,2,992"
// Andrikanych Yevhen 2020
// https://www.youtube.com/c/freelancerlifestyle
"use strict";
(function () {
let originalPositions = [];
let daElements = document.querySelectorAll('[data-da]');
let daElementsArray = [];
let daMatchMedia = [];
//Заполняем массивы
if (daElements.length > 0) {
let number = 0;
for (let index = 0; index < daElements.length; index++) {
const daElement = daElements[index];
const daMove = daElement.getAttribute('data-da');
if (daMove != '') {
const daArray = daMove.split(',');
const daPlace = daArray[1] ? daArray[1].trim() : 'last';
const daBreakpoint = daArray[2] ? daArray[2].trim() : '767';
const daType = daArray[3] === 'min' ? daArray[3].trim() : 'max';
const daDestination = document.querySelector('.' + daArray[0].trim())
if (daArray.length > 0 && daDestination) {
daElement.setAttribute('data-da-index', number);
//Заполняем массив первоначальных позиций
originalPositions[number] = {
"parent": daElement.parentNode,
"index": indexInParent(daElement)
};
//Заполняем массив элементов
daElementsArray[number] = {
"element": daElement,
"destination": document.querySelector('.' + daArray[0].trim()),
"place": daPlace,
"breakpoint": daBreakpoint,
"type": daType
}
number++;
}
}
}
dynamicAdaptSort(daElementsArray);
//Создаем события в точке брейкпоинта
for (let index = 0; index < daElementsArray.length; index++) {
const el = daElementsArray[index];
const daBreakpoint = el.breakpoint;
const daType = el.type;
daMatchMedia.push(window.matchMedia("(" + daType + "-width: " + daBreakpoint + "px)"));
daMatchMedia[index].addListener(dynamicAdapt);
}
}
//Основная функция
function dynamicAdapt(e) {
for (let index = 0; index < daElementsArray.length; index++) {
const el = daElementsArray[index];
const daElement = el.element;
const daDestination = el.destination;
const daPlace = el.place;
const daBreakpoint = el.breakpoint;
const daClassname = "_dynamic_adapt_" + daBreakpoint;
if (daMatchMedia[index].matches) {
//Перебрасываем элементы
if (!daElement.classList.contains(daClassname)) {
let actualIndex = indexOfElements(daDestination)[daPlace];
if (daPlace === 'first') {
actualIndex = indexOfElements(daDestination)[0];
} else if (daPlace === 'last') {
actualIndex = indexOfElements(daDestination)[indexOfElements(daDestination).length];
}
daDestination.insertBefore(daElement, daDestination.children[actualIndex]);
daElement.classList.add(daClassname);
}
} else {
//Возвращаем на место
if (daElement.classList.contains(daClassname)) {
dynamicAdaptBack(daElement);
daElement.classList.remove(daClassname);
}
}
}
customAdapt();
}
//Вызов основной функции
dynamicAdapt();
//Функция возврата на место
function dynamicAdaptBack(el) {
const daIndex = el.getAttribute('data-da-index');
const originalPlace = originalPositions[daIndex];
const parentPlace = originalPlace['parent'];
const indexPlace = originalPlace['index'];
const actualIndex = indexOfElements(parentPlace, true)[indexPlace];
parentPlace.insertBefore(el, parentPlace.children[actualIndex]);
}
//Функция получения индекса внутри родителя
function indexInParent(el) {
var children = Array.prototype.slice.call(el.parentNode.children);
return children.indexOf(el);
}
//Функция получения массива индексов элементов внутри родителя
function indexOfElements(parent, back) {
const children = parent.children;
const childrenArray = [];
for (let i = 0; i < children.length; i++) {
const childrenElement = children[i];
if (back) {
childrenArray.push(i);
} else {
//Исключая перенесенный элемент
if (childrenElement.getAttribute('data-da') == null) {
childrenArray.push(i);
}
}
}
return childrenArray;
}
//Сортировка объекта
function dynamicAdaptSort(arr) {
arr.sort(function (a, b) {
if (a.breakpoint > b.breakpoint) { return -1 } else { return 1 }
});
arr.sort(function (a, b) {
if (a.place > b.place) { return 1 } else { return -1 }
});
}
//Дополнительные сценарии адаптации
function customAdapt() {
//const viewport_width = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
}
}());
/*
let block = document.querySelector('.click');
block.addEventListener("click", function (e) {
alert('Все ок ;)');
});
*/
/*
//Объявляем переменные
const parent_original = document.querySelector('.content__blocks_city');
const parent = document.querySelector('.content__column_river');
const item = document.querySelector('.content__block_item');
//Слушаем изменение размера экрана
window.addEventListener('resize', move);
//Функция
function move(){
const viewport_width = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
if (viewport_width <= 992) {
if (!item.classList.contains('done')) {
parent.insertBefore(item, parent.children[2]);
item.classList.add('done');
}
} else {
if (item.classList.contains('done')) {
parent_original.insertBefore(item, parent_original.children[2]);
item.classList.remove('done');
}
}
}
//Вызываем функцию
move();
*/