diff --git a/js-core/classworks/classwork-17/index.html b/js-core/classworks/classwork-17/index.html new file mode 100644 index 0000000..3a7ed53 --- /dev/null +++ b/js-core/classworks/classwork-17/index.html @@ -0,0 +1,25 @@ + + + + + Lesson_17 + + + + +

Classwork 17

+ +
+ + + + + + \ No newline at end of file diff --git a/js-core/classworks/classwork-17/main.js b/js-core/classworks/classwork-17/main.js new file mode 100644 index 0000000..86ad46b --- /dev/null +++ b/js-core/classworks/classwork-17/main.js @@ -0,0 +1,178 @@ +/* -----------------------PREVIOUS HOMEWORK-------------------------- + + 0 Алгоритмы + Реализуйте функцию которая будет превращать трехмерный массив + в двухмерный, а если массив двухмерный, тогда в трехмерный массив + + ИСПОЛЬЗУЙТЕ МЕТОДЫ МАССИВОВ ! + */ +solution = arr => { +// каким-то образом понять, сколько должно быть на выходе + return arr[0].map((_, index) => { // это чтобы понять, сколько должно быть массивов на выходе + return arr.map((value) => { //value - это в первом случае [1, 3, 5]. Этот ретерн сработает 3 раза, т.е. вернет 3 массива + return value[index];// верни из [1, 3, 5] первое значение, потом второе, потом третье - + // в зависимости от итерации по маленькому массиву + }) + }) + +} +/*Мое решение - так себе +solution = arr => { + let counter = 0; + let resultArray = []; + + while (counter != arr[0].length) { + + let smallArray = arr.map(item => { // [1, 'a'] + return item[counter]; + }) + + resultArray.push(smallArray); + counter++; + } + + return resultArray; + +}*/ +//console.log(solution([ [1, 3, 5], [2, 4, 6] ])) //=> [ [1, 2], [3, 4], [5, 6] ]; +//console.log(solution([ [1, 'a'], [2, 'b'], [3, 'c'] ])) //=> [ [1, 2, 3], [a, b, c] ]; +//console.log(solution([[]]))// => [] +//console.log(solution([ [ [ ] ] ])) // = [ [] ] + + + +//--------------CLASSWORK 17--------------------------- +//------createDocumentFragment-------------------------- +//Создает “виртуальный документ”, в которым можно генерировать разметку и работать с элементами. +//При вставке в документ document fragment исчезает, остается только разметка. +//Удобно при создание виртуальной разметки…. +//css нету + +let myDocument = document.createDocumentFragment(); +const div = document.createElement('div'); +div.textContent = 'qwerty'; + +myDocument.appendChild(div); +document.body.appendChild(myDocument); + +//-------documentWrite----------------------------------- +//напишется прям в том месте дома, где встретился по коду + +//document.write('

qwert

') + +let myNext = document.getElementById('next'); +console.log(myNext); +//сделать по клику, чтобы менялся цвет зеленый-желтый-красный------- +//green +//yellow +//red + +/*myNext.onclick = function(){ + const {style} = next; + + if (style.backgroundColor === 'green') { + style.backgroundColor = 'yellow'; + + } else if (style.backgroundColor === 'yellow'){ + style.backgroundColor = 'red'; + } else { + style.backgroundColor = 'green'; + } + +}*/ + +//сделать, чтобы цвет менялся каждую секунду------------------ + +/*let arr = ['green', 'yellow', 'red']; + +let counter = 0; + +setInterval(()=>{ + next.style.backgroundColor = arr[counter]; + counter++; + if(counter === arr.length) { + counter = 0; + } +}, 1000)*/ + +//увеличивайте ширину next на 10 px каждую 1 сек---------------- +let arr = ['green', 'yellow', 'red']; + +let counter = 0; +//let widthCounter = 10 + +/*setInterval(()=>{ + next.style.backgroundColor = arr[counter]; + const newWidth = parseInt(next.style.width) + 10; + + next.style.width = newWidth + 'px'; + //next.style.left = newWidth + 'px'; + + console.log(next.style.width); + counter++; + if(counter === arr.length) { + counter = 0; + } +}, 100)*/ + +//-----------------------------КЛАССЫ---------------------- +//элемент.className - вернет список классов элемента в виде строки +console.log(next.classList) //выводит весь список классов в виде псевдомассива +//element.classList.contains()//содержит +//element.classList.add()//добавить +//element.classList.remove()//удалить +//element.classList.toggle()//переключить + +//через 1 сек делать квадрат то кругом, то квадратом +setInterval(()=>{ + next.style.backgroundColor = arr[counter]; + //const newWidth = parseInt(next.style.width) + 10; + //next.style.width = newWidth + 'px'; + + next.classList.toggle('active'); + counter++; + if(counter === arr.length) { + counter = 0; + } +}, 500); + +//--------------------------------------- +/*element.clientTop ~ css border, высота бордера верхнего +element.clientLeft ~ css border, ширина левого бордера +element.clientWidth ~ css width + padding - (scroll-bar) +element.clientHeight ~ css height + padding//без единиц измерения, только цифры + +offsetHeight ~ css height + border + padding, То же, что и clientHeight, но возвращает ширину/высоту элемента с учетом и паддинга, и бордера +offsetWidth ~ css width + border + padding +offsetTop - положение сверху относительно offsetParent элемента +offsetLeft - положение слева относительно offsetParent элемента +offsetParent - Свойство offsetParent содержит первый родительский элемент у которого CSS свойство position не равно static, либо body если его нет. + То есть родителя относительно которого происходит позиционирование элемента. */ + +setInterval(()=>{ + next.style.backgroundColor = arr[counter]; + //const newWidth = parseInt(next.style.width) + 10; + //next.style.width = newWidth + 'px'; + + next.classList.toggle('active'); + counter++; + if(counter === arr.length) { + counter = 0; + } +}, 500); + +//element.scrollTop - позиция скролла относительно блока элемента (px) считывает или устанавлиет + // количество пикселей, прокрученных от верха элемента. scrollTop измеряет + // дистанцию от верха элемента до верхней точки видимого контента. Когда контент + // элемента не создаёт вертикальную прокрутку, его scrollTop равно 0. +//element.scrollLeft - позиция скролла относительно горизонтального элемента (px) + +//element.scrollIntoView() - скролл к элементу +//elem.scrollIntoView(true) - Прилепит элемент elem, на котором вызывается метод, к верху страницы +//elem.scrollIntoView(false) - Прилепит элемент elem, на котором вызывается метод, к низу страницы + +//window.pageYOffset - скролл Y относительно окна window. хранит текущую прокрутку страницы в px, не работает в IE +//window.pageXoffset - скролл X относительно окна window. хранит текущую прокрутку страницы в px, не работает в IE + +//document.documentElement.scrollTop - то же самое для IE и FF +//document.body.scrollTop - то же самое, работает в хроме, в файрфоксе не работает diff --git a/js-core/classworks/classwork-18/index.html b/js-core/classworks/classwork-18/index.html new file mode 100644 index 0000000..2790789 --- /dev/null +++ b/js-core/classworks/classwork-18/index.html @@ -0,0 +1,140 @@ + + + + + Lesson_18 + + + + +

Classwork 18

+
+
+
+ +
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + \ No newline at end of file diff --git a/js-core/classworks/classwork-18/main.js b/js-core/classworks/classwork-18/main.js new file mode 100644 index 0000000..84d42a9 --- /dev/null +++ b/js-core/classworks/classwork-18/main.js @@ -0,0 +1,57 @@ +/*DOM EVENTS LEVEL 1*/ +let block1 = document.querySelector('.block1'); +let block2 = document.querySelector('.block2'); +let block3 = document.querySelector('.block3'); + +/*block1.addEventListener('click', function(){ + console.log('I am block1'); +}, false); + +block2.addEventListener('click', function(){ + console.log('I am block2'); +}, false);*/ + +block3.addEventListener('click', clickHandler); + +let counter = 0; +function clickHandler(){ + if (counter < 3) { + console.log('I am block3'); + counter++; + return; + } + + block3.removeEventListener('click', clickHandler); + console.log('eventListener was deleted'); +} + +//3 параметр - всплытие +//по умолчанию стоит false +//по умолчанию ловятся события на всплытии +//но если при погружении джаваскрипту встретится событие, у которого true, +//то сначала выполнится событие с true, потом целевое событие, потом события, +//которые на блоках выше и у которых false + +/*let table = document.querySelector('table'); + +table.addEventListener('click', function(){ + + if (!event && !event.target) { + return; + }; + + let target = event.target; + if (target.tagName != "TD") { + return; + }; + target.style.background = 'red'; + +});*/ + +//event.stopPropagation(); - остановка всплытия или погружения, т.е. если это написать +//в ф-ции, т. выполнится только это событие и никакие более высокие не выполнятся + +//event.stopImmediatePropogation() - остановит на всплытии вообще все последующие события + +//preventDefault() - останавливает поведение по умолчанию, например, переход по ссылке + diff --git a/js-core/homeworks/homework-17/img/img1.jpg b/js-core/homeworks/homework-17/img/img1.jpg new file mode 100644 index 0000000..9c96b73 Binary files /dev/null and b/js-core/homeworks/homework-17/img/img1.jpg differ diff --git a/js-core/homeworks/homework-17/img/img2.jpg b/js-core/homeworks/homework-17/img/img2.jpg new file mode 100644 index 0000000..64cb649 Binary files /dev/null and b/js-core/homeworks/homework-17/img/img2.jpg differ diff --git a/js-core/homeworks/homework-17/img/img3.jpg b/js-core/homeworks/homework-17/img/img3.jpg new file mode 100644 index 0000000..ff570ee Binary files /dev/null and b/js-core/homeworks/homework-17/img/img3.jpg differ diff --git a/js-core/homeworks/homework-17/index.html b/js-core/homeworks/homework-17/index.html new file mode 100644 index 0000000..d690d7f --- /dev/null +++ b/js-core/homeworks/homework-17/index.html @@ -0,0 +1,64 @@ + + + + + Homework 17 + + + +

Homework 17

+
+ + + + +
+ + + + \ No newline at end of file diff --git a/js-core/homeworks/homework-17/main.js b/js-core/homeworks/homework-17/main.js new file mode 100644 index 0000000..657ed2a --- /dev/null +++ b/js-core/homeworks/homework-17/main.js @@ -0,0 +1,307 @@ +/* + TASK 0---------------------------------------------------------------- + Отобразите всех лидеров массива. + * + * + * Элемент лидер если он больше чем все последующие элементы + * после него ( элементы справа ). + * Последний элемент всегда лидер. Например в массиве [16,17,4,3,5,2] + * лидеры 17, 5 и 2. + * + * */ + +const solution = arr => { +}; + +//console.log(solution([16, 17, 4, 3, 5, 2])); // === [17, 5, 2] +//console.log(solution([4, 3, 7, 12, 6, 67, 5, 45, 34, 35, 2, 8])); // [67, 45, 35, 8] +//console.log(solution([12, 10, 12, 8, 7, 6])); // [12, 8, 7, 6] +//console.log(solution([1, 2, 3, 4, 5, 4])); // [5, 4] +//console.log(solution([12, 12, 12])); // [5, 4] + +/* TASK 1-------------------------------------------------------------- + * Сделайте карусель. + * При клике по кнопке "<=" показывается первое изображение по "=>" следующее. + * + 1.1 + * Сделайте слайдер - бесконечным, после третьего изображения снова первое. + * 1.2 + * Добавьте внизу цифры с текущим активным изображением. + */ + /*создайте новый instance Carouse при вызове initialize*/ //не поняла, что это значит +/*var myInitializedCarousel = Carousel.initialize({ + elementToApply: '.carousel', + infinity: true, +});*/ + + +/*class Carousel { + + static initialize() { + return new Carousel; + } + + constructor(){ + this.clickHandler(); + } + + clickHandler() { + let leftArrow = document.querySelector('.ec-left'); + let rightArrow = document.querySelector('.ec-right'); + let slides = [...document.querySelectorAll('li')]; + let activeNumberSpan = document.querySelector('.number'); + let activeSlide = null; + + slides.forEach((item) => { + if (item.getAttribute('style') == 'display: block') { + activeSlide = item; + activeNumberSpan.innerHTML = activeSlide.firstElementChild.alt; + } + }); + + leftArrow.onclick = () => { + activeSlide.setAttribute('style', 'display:none'); + if (activeSlide.previousElementSibling) { + activeSlide.previousElementSibling.setAttribute('style', 'display:block'); + activeSlide = activeSlide.previousElementSibling; + activeNumberSpan.innerHTML = activeSlide.firstElementChild.alt; + + } else { + slides[slides.length - 1].setAttribute('style', 'display:block'); + activeSlide = slides[slides.length - 1]; + activeNumberSpan.innerHTML = activeSlide.firstElementChild.alt; + } + + } + + rightArrow.onclick = () => { + activeSlide.setAttribute('style', 'display:none'); + if (activeSlide.nextElementSibling) { + activeSlide.nextElementSibling.setAttribute('style', 'display:block'); + activeSlide = activeSlide.nextElementSibling; + activeNumberSpan.innerHTML = activeSlide.firstElementChild.alt; + } else { + slides[0].setAttribute('style', 'display:block'); + activeSlide = slides[0]; + activeNumberSpan.innerHTML = activeSlide.firstElementChild.alt; + } + + } + + } + +} +//let myCarousel = new Carousel; +var myInitializedCarousel = Carousel.initialize(); +*/ + + + /* @SUPER -> @front-end--------------------------------------------------- + * Уберите в стилях li - position:absolute. + * изменяйте свойство transform:translate3d у .carousel, добавьте transition + * и сделайте чтобы картинки передвигались влево и вправо + * + * @PUPER -> переход к первой картинка------------------------------------- + * + * */ +class Carousel { + + static initialize() { + return new Carousel; + } + + constructor(){ + this.clickHandler(); + } + + clickHandler() { + let leftArrow = document.querySelector('.ec-left'); + let rightArrow = document.querySelector('.ec-right'); + + this.parent = document.querySelector('ul'); + this.slides = [...this.parent.children]; + + this.oneChildWidth = parseInt(getComputedStyle(this.slides[0]).width); + let parentWidth = this.oneChildWidth * this.slides.length; + this.parent.style.width = parentWidth + 'px'; + + this.activeSlide = this.parent.firstElementChild; + + let activeNumberSpan = document.querySelector('.number'); + activeNumberSpan.innerHTML = this.activeSlide.firstElementChild.alt; + + + leftArrow.onclick = () => { + + if (this.activeSlide.nextElementSibling) { + + this.changeSlide(leftArrow); + + } else { + + this.parent.style.transform = `translateX(0px)`; + this.activeSlide = this.parent.firstElementChild; + } + + activeNumberSpan.innerHTML = this.activeSlide.firstElementChild.alt; + } + + rightArrow.onclick = () => { + + if (this.activeSlide.previousElementSibling) { + + this.changeSlide(rightArrow); + + } else { + + this.parent.style.transform = `translateX(-${this.oneChildWidth*(this.slides.length-1)}px)`; + this.activeSlide = this.parent.lastElementChild; + + } + + activeNumberSpan.innerHTML = this.activeSlide.firstElementChild.alt; + } + + } + + changeSlide(arrow){ + if (arrow.classList.contains('ec-left')) { + this.parent.style.transform += `translateX(-${this.oneChildWidth}px)`; + this.activeSlide = this.activeSlide.nextElementSibling; + } else { + this.parent.style.transform += `translateX(${this.oneChildWidth}px)`; + this.activeSlide = this.activeSlide.previousElementSibling; + } + + } + +} + + +//let myCarousel = new Carousel; +var myInitializedCarousel = Carousel.initialize( + //{ + //elementToApply: '.carousel', + //infinity: true, + //} +); + + +/* +* TASK 2--------------------------------------------------------------------- +* Сделайте класс, который будет иметь метод topStyle +* метод topStyle принимает объект с CSS стилями и добавляет в +* новый элемент с данными стилями +* +* +* */ +// .topStyle('fetch', {backgroundColor:'blue'}) +/* +* +* + + + +
+
+
+
+
+
+
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+ + + + \ No newline at end of file diff --git a/js-core/homeworks/homework-18/main.js b/js-core/homeworks/homework-18/main.js new file mode 100644 index 0000000..68b663f --- /dev/null +++ b/js-core/homeworks/homework-18/main.js @@ -0,0 +1,160 @@ +/* EASY--------------------------------------------------------- +Алгоритмы ! +TASK 0 +Вам дано предложение, верните массив из слов, +которые длинее чем средняя длина всех слов. +Слова разделены пробелами, если в предложении запятые,они должны быть пропущены*/ +function solution(arr){ + let wordsArray = arr[0].split(' '); + let pattern = /\W/g; + let onlyWords = []; + + let itemsLength = wordsArray.reduce((newItem, item) => { + + if (item.search(pattern) > -1){ + item = item.replace(pattern, ''); + } + + onlyWords.push(item); + return newItem + item.length; + + }, 0); + + let averageLength = Math.floor(itemsLength / wordsArray.length); + + let result = onlyWords.filter((item) => { + if (item.length > averageLength) { + return item; + } + }) + + return result; +} + +console.log(solution(["This is a sample string"])) //expected ["This" "sample" "string"] +console.log(solution(["Some another sample"])) //expected ["another" "sample"] +console.log(solution(["Do, do, do, do... do it!"])) //expected [] + + +/* +Подготовка к занятию в пятницу.-----------DONE------------------------------------------- +Windows: + Установите все node.js скачать отсюда -> https://nodejs.org/en/ + Скачайте последнюю 10.x.x версию + Для проверки установки в консоле введите "node -v" (без кавычек) отобразит версию node.js +Linux: + sudo apt install npm // установить менеджер пакетов npm + npm i -g n // установить пакет для установки node.js + sudo n latest // установить последнюю версию node.js +*/ + + +/* TASK 1------------------------------------------------------------------------------- +Сделайте таблицу 5x5 +При клике на элемент, изменяйте цвет у элемента на красный. +Но цвет у элемента должен изменяться пропорционально в другой половине квадрата +Пример 3х3: +[]|[]|[] +[]|[]|[] +[]|[]|[] +кликаем сюда -> []|[]|[] + []|[]|[] + []|[]|[x] <- загорается тут + + []|[]|[] +кликаем сюда -> []|[]|[x] <- загорается тут + []|[]|[x] +*/ +let table = document.querySelector('table'); +table.addEventListener('click', makeItRed); +//let coloredTD; + +function makeItRed(){ + let target = event && event.target; + + if (target.tagName == 'TD') { + target.textContent = ' '; + + let rowsChildren = [...target.parentNode.parentNode.children]; + let clickedRow = target.parentNode; + + rowsChildren.forEach((row, j, rowsArr) => { + if(clickedRow == row){ + + let clickedIndexRow = j+1; + + let shouldBeColoredRow = rowsArr.length - clickedIndexRow; + + [...row.children].forEach((td, i, tdsArr) => { + + if (td.textContent == ' ') { + + let clickedIndex = i+1; + let shouldBeColoredIndex = tdsArr.length - clickedIndex; + let shouldBeColoredTD = [...rowsArr[shouldBeColoredRow].children][shouldBeColoredIndex]; + + toPaint(shouldBeColoredTD); + + return; + } + }) + } // end of if + + }) // end of rowsChildren.forEach + + } // end of if + +} // end of function + +function toPaint(elem){ //I want to remove bg color from previous colored element, but it works in strange way + //if (coloredTD) { + // coloredTD.classList.remove('painted'); + //} + + //coloredTD = elem; + //coloredTD.classList.add('painted'); + elem.classList.add('painted'); +} + +// @SUPER-FrontEnd---------------------------------------------------------------- +/* +У вас есть 3 блока смотри events.html +при mousedown и движении мышки нужно сделать +ресайз одного блока. +Подсказка - событие необходимо повесить на доп. элемент .resize +*/ + +class Resize { + constructor(){ + this.parent = document.querySelector('section'); + this.parent.addEventListener('mousedown', this.handlerMouseDown.bind(this)); + this.handlerMouseMove = this.handlerMouseMove.bind(this); + window.addEventListener('mouseup', this.handlerMouseUp.bind(this)); + } + + handlerMouseDown(e){ + this.target = e.target; + this.startMouseX = e.clientX; + //this.initialWidth = this.target.parentNode.offsetWidth; + + if (this.target && this.target.classList.contains('resize')) { + window.addEventListener('mousemove', this.handlerMouseMove); + } + } + + handlerMouseMove(e) { + //let startMouseX = e.clientX; + let endMouseX = e.clientX; // собирает координаты мыши все время, пока происходит движение + + //if (endMouseX > this.startMouseX) { + this.target.parentNode.style.cssText = `flex-basis:${endMouseX-this.startMouseX}px;`; + //} + } + + handlerMouseUp(){ + window.removeEventListener('mousemove', this.handlerMouseMove); + } + +} + +let newResize = new Resize();