Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Массив с данными карточек
- // const initialCards = [
- // {
- // name: "Архыз",
- // link:
- // "https://pictures.s3.yandex.net/frontend-developer/cards-compressed/arkhyz.jpg"
- // },
- // {
- // name: "Челябинская область",
- // link:
- // "https://pictures.s3.yandex.net/frontend-developer/cards-compressed/chelyabinsk-oblast.jpg"
- // },
- // {
- // name: "Иваново",
- // link:
- // "https://pictures.s3.yandex.net/frontend-developer/cards-compressed/ivanovo.jpg"
- // },
- // {
- // name: "Камчатка",
- // link:
- // "https://pictures.s3.yandex.net/frontend-developer/cards-compressed/kamchatka.jpg"
- // },
- // {
- // name: "Холмогорский район",
- // link:
- // "https://pictures.s3.yandex.net/frontend-developer/cards-compressed/kholmogorsky-rayon.jpg"
- // },
- // {
- // name: "Байкал",
- // link:
- // "https://pictures.s3.yandex.net/frontend-developer/cards-compressed/baikal.jpg"
- // },
- // {
- // name: "Нургуш",
- // link:
- // "https://pictures.s3.yandex.net/frontend-developer/cards-compressed/khrebet-nurgush.jpg"
- // },
- // {
- // name: "Тулиновка",
- // link:
- // "https://pictures.s3.yandex.net/frontend-developer/cards-compressed/tulinovka.jpg"
- // },
- // {
- // name: "Остров Желтухина",
- // link:
- // "https://pictures.s3.yandex.net/frontend-developer/cards-compressed/zheltukhin-island.jpg"
- // },
- // {
- // name: "Владивосток",
- // link:
- // "https://pictures.s3.yandex.net/frontend-developer/cards-compressed/vladivostok.jpg"
- // }
- // ];
- class CardListClass {
- constructor(container, arrayData) {
- this.container = container;
- this.arrayData = arrayData;
- this.render();
- }
- addCard(nameCard, linkCard) {
- this.container.appendChild(Card.create(nameCard, linkCard));
- }
- render() {
- for (let i = 0; i < this.arrayData.length; i++) {
- this.addCard(this.arrayData[i].name, this.arrayData[i].link);
- }
- }
- }
- class Card {
- constructor(name, linkPic) {
- this.name = name;
- this.linkPic = linkPic;
- this.element = Card.create(this.name, this.linkPic);
- }
- static create(name, linkPic) {
- const card = document.createElement("div");
- // Создаем основной div
- const newCard = document.createElement("div");
- newCard.classList.add("place-card");
- card.appendChild(newCard);
- // Создаем div для фона и кнопки "удалить карту"
- const imageContainer = document.createElement("div");
- imageContainer.classList.add("place-card__image");
- newCard.appendChild(imageContainer);
- imageContainer.setAttribute("style", `background-image: url(${linkPic})`);
- const deleteBtn = document.createElement("button");
- deleteBtn.classList.add("place-card__delete-icon");
- imageContainer.appendChild(deleteBtn);
- // Создаем div для контейнера имени и кнопки "лайк"
- const descriptionContainer = document.createElement("div");
- descriptionContainer.classList.add("place-card__description");
- newCard.appendChild(descriptionContainer);
- // Создаем имя карточки
- const newName = document.createElement("h3");
- newName.classList.add("place-card__name");
- newName.textContent = `${name}`;
- descriptionContainer.appendChild(newName);
- // Создаем кнопку "лайк"
- const likeBtn = document.createElement("button");
- likeBtn.classList.add("place-card__like-icon");
- descriptionContainer.appendChild(likeBtn);
- return card;
- }
- static like(element) {
- element.classList.toggle("place-card__like-icon_liked");
- }
- static remove() {
- const card = event.target.parentElement.parentElement.parentElement;
- card.parentElement.removeChild(card);
- }
- }
- class Popup {
- constructor(element, openClassName, closeElement) {
- this.element = element;
- this.openClassName = openClassName;
- closeElement.addEventListener("click", () => this.close());
- }
- open() {
- this.element.classList.add(this.openClassName);
- }
- close() {
- this.element.classList.remove(this.openClassName);
- }
- }
- fetch('http://95.216.175.5/cohort1/cards', {
- method: 'GET',
- headers: {
- authorization: 'a22615e2-6b60-43bf-b944-bd524da74e3e'
- }
- })
- .then((res) => {
- return res.json()
- })
- .then((result) => {
- for(i = 0; i < result.length; i++) {
- const initialCards = {};
- initialCards.name = result[i].name;
- initialCards.link = result[i].link;
- console.log(initialCards);
- }
- })
- const cardListRender = new CardListClass(document.querySelector(".places-list"),initialCards);
- // Переменные
- // Карточки
- const cardList = document.querySelector(".places-list");
- const card = document.querySelector(".place-card");
- const image = document.querySelector(".place-card__image");
- const like = document.querySelector(".place-card__like-icon");
- const deleteCard = document.querySelector(".place-card__delete-icon");
- // Попап с новой карточкой
- const popup = document.querySelector(".popup");
- const openAddCardPopup = document.querySelector(".user-info__button");
- const closeAddPopupBtn = document.querySelector(".popup__close");
- const popupForm = document.querySelector(".popup__form");
- const postBtn = document.querySelector(".popup__button");
- const placeName = document.querySelector(".popup__input_type_name");
- const placeImage = document.querySelector(".popup__input_type_link-url");
- // Попап с редактированием профиля
- const popupEdit = document.querySelector(".popup-edit");
- const openEditPopup = document.querySelector(".user-info__button-edit");
- const closeEditPopupBtn = document.querySelector(".popup-edit__close");
- const popupEditForm = document.querySelector(".popup-edit__form");
- const userName = document.querySelector(".user-info__name");
- const userJob = document.querySelector(".user-info__job");
- const inputUserName = document.querySelector(".popup-edit__input_type_name");
- const inputUserAbout = document.querySelector(".popup-edit__input_type_about");
- const editBtn = document.querySelector(".popup-edit__button");
- // Попап с увеличением картинки
- const popupBigImg = document.querySelector(".popup-bigimg");
- const popupBigImgSrc = document.querySelector(".popup-bigimg__image");
- const popupBigImgSrcDefault = image.getAttribute("style");
- // Элементы для валидации
- const errorElement = document.querySelector(`.error-message`);
- // Использование классов
- const editFormPopup = new Popup(popupEdit,"popup-edit_is-opened",closeEditPopupBtn
- );
- const newCardFormPopup = new Popup(popup, "popup_is-opened", closeAddPopupBtn);
- // Слушатели
- // Открыть попап редактирования профиля
- openEditPopup.addEventListener("click", () => {
- editFormPopup.open();
- inputUserName.value = userName.textContent;
- inputUserAbout.value = userJob.textContent;
- });
- // Открыть попап добавления карточки
- openAddCardPopup.addEventListener("click", () => {
- newCardFormPopup.open();
- // Очистка полей вода
- postBtn.classList.remove("popup__button_enabled");
- postBtn.setAttribute("disabled", true);
- placeName.value = "";
- placeImage.value = "";
- });
- // Submit формы на click и enter
- popupForm.addEventListener("submit", function(event) {
- event.preventDefault();
- const card = new Card(placeName.value, placeImage.value);
- const cardElement = card.element;
- cardList.appendChild(cardElement);
- postBtn.classList.remove("popup__button_enabled");
- postBtn.setAttribute("disabled", true);
- popup.classList.remove("popup_is-opened");
- });
- // Лайк и удаление
- cardList.addEventListener("click", function(event) {
- // Поставить/снять лайк
- if (event.target.classList.contains("place-card__like-icon")) {
- Card.like(event.target);
- }
- // Удалить карточку
- if (event.target.classList.contains("place-card__delete-icon")) {
- Card.remove(event.target);
- }
- });
- // Изменение имени в профиле
- popupEditForm.addEventListener("submit", function(event) {
- event.preventDefault();
- userName.textContent = inputUserName.value;
- userJob.textContent = inputUserAbout.value;
- popupEdit.classList.remove("popup-edit_is-opened");
- });
- // Открытие попапа с увеличением картинки
- cardList.addEventListener("click", function(event) {
- let url = event.target.getAttribute("style");
- const startUrlSlice = 22;
- const endUrlSlice = -1;
- if (event.target.classList.contains("place-card__image")) {
- let urlSlice = url.slice(startUrlSlice, endUrlSlice);
- popupBigImg.classList.add("popup-bigimg_is-opened");
- popupBigImgSrc.setAttribute("src", `${urlSlice}`);
- }
- });
- // Закрытие попапа с увеличением картинки
- popupBigImg.addEventListener("click", function(event) {
- if (event.target.classList.contains("popup-bigimg__close")) {
- popupBigImg.classList.remove("popup-bigimg_is-opened");
- }
- });
- // Валидация
- // Валидация кнопки сохранить
- popupEdit.addEventListener("input", function() {
- if (inputUserName.value.length >= 2 && inputUserAbout.value.length >= 2) {
- editBtn.classList.add("popup-edit__button_enabled");
- } else {
- editBtn.classList.remove("popup-edit__button_enabled");
- }
- });
- // Валидация кнопки новое место
- popup.addEventListener("input", function() {
- if (placeName.value.length !== 0 && placeImage.value.length !== 0) {
- postBtn.classList.add("popup__button_enabled");
- postBtn.removeAttribute("disabled");
- } else {
- postBtn.classList.remove("popup__button_enabled");
- postBtn.setAttribute("disabled", true);
- }
- });
- inputUserName.addEventListener("input", handleValidate);
- inputUserAbout.addEventListener("input", handleValidate);
- // Колбэк для слушателей валидации
- function handleValidate(event) {
- validate(event.target);
- }
- // Активация ошибки валидации
- function activateError(element) {
- const errorMessage = document.querySelector(`#${element.id}`);
- errorMessage.classList.add("error-message_active");
- }
- // Функция валидации
- function validate(element) {
- const errorElement = document.querySelector(`#error-${element.id}`);
- if (element.value.length === 0) {
- const errorMessage = "Это обязательное поле";
- errorElement.textContent = errorMessage;
- activateError(errorElement);
- return false;
- } else if (element.value.length <= 1 || element.value.length >= 30) {
- const errorMessage = "Должно быть от 2 до 30 символов";
- errorElement.textContent = errorMessage;
- activateError(errorElement);
- return false;
- }
- errorElement.classList.remove("error-message_active");
- errorElement.textContent = "";
- return true;
- }
- // Токен - a22615e2-6b60-43bf-b944-bd524da74e3e
- // Группа - cohort1
- // IP - 95.216.175.5
- // fetch('http://95.216.175.5/cohort1/cards', {
- // headers: {
- // authorization: 'a22615e2-6b60-43bf-b944-bd524da74e3e'
- // }
- // })
- // .then(res => res.json())
- // .then((result) => {
- // console.log(result);
- // });
- class Api {
- constructor(options) {
- // тело конструктора
- }
- getInitialCards() {
- // ...
- }
- // другие методы работы с API
- }
- const api = new Api({
- baseUrl: 'http://95.216.175.5/cohort42',
- headers: {
- authorization: 'c56e30dc-2883-4270-a59e-b2f7bae969c6',
- 'Content-Type': 'application/json'
- }
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement