Advertisement
Guest User

Untitled

a guest
Jul 24th, 2019
1,535
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.95 KB | None | 0 0
  1. // Массив с данными карточек
  2. // const initialCards = [
  3. // {
  4. // name: "Архыз",
  5. // link:
  6. // "https://pictures.s3.yandex.net/frontend-developer/cards-compressed/arkhyz.jpg"
  7. // },
  8. // {
  9. // name: "Челябинская область",
  10. // link:
  11. // "https://pictures.s3.yandex.net/frontend-developer/cards-compressed/chelyabinsk-oblast.jpg"
  12. // },
  13. // {
  14. // name: "Иваново",
  15. // link:
  16. // "https://pictures.s3.yandex.net/frontend-developer/cards-compressed/ivanovo.jpg"
  17. // },
  18. // {
  19. // name: "Камчатка",
  20. // link:
  21. // "https://pictures.s3.yandex.net/frontend-developer/cards-compressed/kamchatka.jpg"
  22. // },
  23. // {
  24. // name: "Холмогорский район",
  25. // link:
  26. // "https://pictures.s3.yandex.net/frontend-developer/cards-compressed/kholmogorsky-rayon.jpg"
  27. // },
  28. // {
  29. // name: "Байкал",
  30. // link:
  31. // "https://pictures.s3.yandex.net/frontend-developer/cards-compressed/baikal.jpg"
  32. // },
  33. // {
  34. // name: "Нургуш",
  35. // link:
  36. // "https://pictures.s3.yandex.net/frontend-developer/cards-compressed/khrebet-nurgush.jpg"
  37. // },
  38. // {
  39. // name: "Тулиновка",
  40. // link:
  41. // "https://pictures.s3.yandex.net/frontend-developer/cards-compressed/tulinovka.jpg"
  42. // },
  43. // {
  44. // name: "Остров Желтухина",
  45. // link:
  46. // "https://pictures.s3.yandex.net/frontend-developer/cards-compressed/zheltukhin-island.jpg"
  47. // },
  48. // {
  49. // name: "Владивосток",
  50. // link:
  51. // "https://pictures.s3.yandex.net/frontend-developer/cards-compressed/vladivostok.jpg"
  52. // }
  53. // ];
  54.  
  55. class CardListClass {
  56. constructor(container, arrayData) {
  57. this.container = container;
  58. this.arrayData = arrayData;
  59. this.render();
  60. }
  61.  
  62. addCard(nameCard, linkCard) {
  63. this.container.appendChild(Card.create(nameCard, linkCard));
  64. }
  65.  
  66. render() {
  67. for (let i = 0; i < this.arrayData.length; i++) {
  68. this.addCard(this.arrayData[i].name, this.arrayData[i].link);
  69. }
  70. }
  71. }
  72.  
  73. class Card {
  74. constructor(name, linkPic) {
  75. this.name = name;
  76. this.linkPic = linkPic;
  77. this.element = Card.create(this.name, this.linkPic);
  78. }
  79.  
  80. static create(name, linkPic) {
  81. const card = document.createElement("div");
  82. // Создаем основной div
  83. const newCard = document.createElement("div");
  84. newCard.classList.add("place-card");
  85.  
  86. card.appendChild(newCard);
  87.  
  88. // Создаем div для фона и кнопки "удалить карту"
  89. const imageContainer = document.createElement("div");
  90. imageContainer.classList.add("place-card__image");
  91. newCard.appendChild(imageContainer);
  92. imageContainer.setAttribute("style", `background-image: url(${linkPic})`);
  93.  
  94. const deleteBtn = document.createElement("button");
  95. deleteBtn.classList.add("place-card__delete-icon");
  96. imageContainer.appendChild(deleteBtn);
  97.  
  98. // Создаем div для контейнера имени и кнопки "лайк"
  99. const descriptionContainer = document.createElement("div");
  100. descriptionContainer.classList.add("place-card__description");
  101. newCard.appendChild(descriptionContainer);
  102.  
  103. // Создаем имя карточки
  104. const newName = document.createElement("h3");
  105. newName.classList.add("place-card__name");
  106. newName.textContent = `${name}`;
  107. descriptionContainer.appendChild(newName);
  108.  
  109. // Создаем кнопку "лайк"
  110. const likeBtn = document.createElement("button");
  111. likeBtn.classList.add("place-card__like-icon");
  112. descriptionContainer.appendChild(likeBtn);
  113.  
  114. return card;
  115. }
  116.  
  117. static like(element) {
  118. element.classList.toggle("place-card__like-icon_liked");
  119. }
  120.  
  121. static remove() {
  122. const card = event.target.parentElement.parentElement.parentElement;
  123. card.parentElement.removeChild(card);
  124. }
  125. }
  126.  
  127. class Popup {
  128. constructor(element, openClassName, closeElement) {
  129. this.element = element;
  130. this.openClassName = openClassName;
  131. closeElement.addEventListener("click", () => this.close());
  132. }
  133.  
  134. open() {
  135. this.element.classList.add(this.openClassName);
  136. }
  137.  
  138. close() {
  139. this.element.classList.remove(this.openClassName);
  140. }
  141. }
  142.  
  143. fetch('http://95.216.175.5/cohort1/cards', {
  144. method: 'GET',
  145. headers: {
  146. authorization: 'a22615e2-6b60-43bf-b944-bd524da74e3e'
  147. }
  148. })
  149. .then((res) => {
  150. return res.json()
  151. })
  152. .then((result) => {
  153. for(i = 0; i < result.length; i++) {
  154. const initialCards = {};
  155. initialCards.name = result[i].name;
  156. initialCards.link = result[i].link;
  157. console.log(initialCards);
  158. }
  159. })
  160.  
  161. const cardListRender = new CardListClass(document.querySelector(".places-list"),initialCards);
  162.  
  163. // Переменные
  164. // Карточки
  165. const cardList = document.querySelector(".places-list");
  166. const card = document.querySelector(".place-card");
  167. const image = document.querySelector(".place-card__image");
  168. const like = document.querySelector(".place-card__like-icon");
  169. const deleteCard = document.querySelector(".place-card__delete-icon");
  170.  
  171. // Попап с новой карточкой
  172. const popup = document.querySelector(".popup");
  173. const openAddCardPopup = document.querySelector(".user-info__button");
  174. const closeAddPopupBtn = document.querySelector(".popup__close");
  175. const popupForm = document.querySelector(".popup__form");
  176. const postBtn = document.querySelector(".popup__button");
  177. const placeName = document.querySelector(".popup__input_type_name");
  178. const placeImage = document.querySelector(".popup__input_type_link-url");
  179.  
  180. // Попап с редактированием профиля
  181. const popupEdit = document.querySelector(".popup-edit");
  182. const openEditPopup = document.querySelector(".user-info__button-edit");
  183. const closeEditPopupBtn = document.querySelector(".popup-edit__close");
  184. const popupEditForm = document.querySelector(".popup-edit__form");
  185. const userName = document.querySelector(".user-info__name");
  186. const userJob = document.querySelector(".user-info__job");
  187. const inputUserName = document.querySelector(".popup-edit__input_type_name");
  188. const inputUserAbout = document.querySelector(".popup-edit__input_type_about");
  189. const editBtn = document.querySelector(".popup-edit__button");
  190.  
  191. // Попап с увеличением картинки
  192. const popupBigImg = document.querySelector(".popup-bigimg");
  193. const popupBigImgSrc = document.querySelector(".popup-bigimg__image");
  194. const popupBigImgSrcDefault = image.getAttribute("style");
  195.  
  196. // Элементы для валидации
  197. const errorElement = document.querySelector(`.error-message`);
  198.  
  199. // Использование классов
  200. const editFormPopup = new Popup(popupEdit,"popup-edit_is-opened",closeEditPopupBtn
  201. );
  202. const newCardFormPopup = new Popup(popup, "popup_is-opened", closeAddPopupBtn);
  203.  
  204. // Слушатели
  205. // Открыть попап редактирования профиля
  206. openEditPopup.addEventListener("click", () => {
  207. editFormPopup.open();
  208. inputUserName.value = userName.textContent;
  209. inputUserAbout.value = userJob.textContent;
  210. });
  211.  
  212. // Открыть попап добавления карточки
  213. openAddCardPopup.addEventListener("click", () => {
  214. newCardFormPopup.open();
  215.  
  216. // Очистка полей вода
  217. postBtn.classList.remove("popup__button_enabled");
  218. postBtn.setAttribute("disabled", true);
  219.  
  220. placeName.value = "";
  221. placeImage.value = "";
  222. });
  223.  
  224. // Submit формы на click и enter
  225. popupForm.addEventListener("submit", function(event) {
  226. event.preventDefault();
  227.  
  228. const card = new Card(placeName.value, placeImage.value);
  229. const cardElement = card.element;
  230. cardList.appendChild(cardElement);
  231.  
  232. postBtn.classList.remove("popup__button_enabled");
  233. postBtn.setAttribute("disabled", true);
  234. popup.classList.remove("popup_is-opened");
  235. });
  236.  
  237. // Лайк и удаление
  238. cardList.addEventListener("click", function(event) {
  239. // Поставить/снять лайк
  240. if (event.target.classList.contains("place-card__like-icon")) {
  241. Card.like(event.target);
  242. }
  243. // Удалить карточку
  244. if (event.target.classList.contains("place-card__delete-icon")) {
  245. Card.remove(event.target);
  246. }
  247. });
  248.  
  249. // Изменение имени в профиле
  250. popupEditForm.addEventListener("submit", function(event) {
  251. event.preventDefault();
  252.  
  253. userName.textContent = inputUserName.value;
  254. userJob.textContent = inputUserAbout.value;
  255. popupEdit.classList.remove("popup-edit_is-opened");
  256. });
  257.  
  258. // Открытие попапа с увеличением картинки
  259. cardList.addEventListener("click", function(event) {
  260. let url = event.target.getAttribute("style");
  261. const startUrlSlice = 22;
  262. const endUrlSlice = -1;
  263.  
  264. if (event.target.classList.contains("place-card__image")) {
  265. let urlSlice = url.slice(startUrlSlice, endUrlSlice);
  266. popupBigImg.classList.add("popup-bigimg_is-opened");
  267. popupBigImgSrc.setAttribute("src", `${urlSlice}`);
  268. }
  269. });
  270.  
  271. // Закрытие попапа с увеличением картинки
  272. popupBigImg.addEventListener("click", function(event) {
  273. if (event.target.classList.contains("popup-bigimg__close")) {
  274. popupBigImg.classList.remove("popup-bigimg_is-opened");
  275. }
  276. });
  277.  
  278. // Валидация
  279. // Валидация кнопки сохранить
  280. popupEdit.addEventListener("input", function() {
  281. if (inputUserName.value.length >= 2 && inputUserAbout.value.length >= 2) {
  282. editBtn.classList.add("popup-edit__button_enabled");
  283. } else {
  284. editBtn.classList.remove("popup-edit__button_enabled");
  285. }
  286. });
  287.  
  288. // Валидация кнопки новое место
  289. popup.addEventListener("input", function() {
  290. if (placeName.value.length !== 0 && placeImage.value.length !== 0) {
  291. postBtn.classList.add("popup__button_enabled");
  292. postBtn.removeAttribute("disabled");
  293. } else {
  294. postBtn.classList.remove("popup__button_enabled");
  295. postBtn.setAttribute("disabled", true);
  296. }
  297. });
  298.  
  299. inputUserName.addEventListener("input", handleValidate);
  300. inputUserAbout.addEventListener("input", handleValidate);
  301.  
  302. // Колбэк для слушателей валидации
  303. function handleValidate(event) {
  304. validate(event.target);
  305. }
  306.  
  307. // Активация ошибки валидации
  308. function activateError(element) {
  309. const errorMessage = document.querySelector(`#${element.id}`);
  310. errorMessage.classList.add("error-message_active");
  311. }
  312.  
  313. // Функция валидации
  314. function validate(element) {
  315. const errorElement = document.querySelector(`#error-${element.id}`);
  316. if (element.value.length === 0) {
  317. const errorMessage = "Это обязательное поле";
  318. errorElement.textContent = errorMessage;
  319. activateError(errorElement);
  320. return false;
  321. } else if (element.value.length <= 1 || element.value.length >= 30) {
  322. const errorMessage = "Должно быть от 2 до 30 символов";
  323. errorElement.textContent = errorMessage;
  324. activateError(errorElement);
  325. return false;
  326. }
  327.  
  328. errorElement.classList.remove("error-message_active");
  329. errorElement.textContent = "";
  330. return true;
  331. }
  332.  
  333.  
  334. // Токен - a22615e2-6b60-43bf-b944-bd524da74e3e
  335. // Группа - cohort1
  336. // IP - 95.216.175.5
  337.  
  338. // fetch('http://95.216.175.5/cohort1/cards', {
  339. // headers: {
  340. // authorization: 'a22615e2-6b60-43bf-b944-bd524da74e3e'
  341. // }
  342. // })
  343. // .then(res => res.json())
  344. // .then((result) => {
  345. // console.log(result);
  346. // });
  347.  
  348. class Api {
  349. constructor(options) {
  350. // тело конструктора
  351. }
  352.  
  353. getInitialCards() {
  354. // ...
  355. }
  356.  
  357. // другие методы работы с API
  358. }
  359.  
  360. const api = new Api({
  361. baseUrl: 'http://95.216.175.5/cohort42',
  362. headers: {
  363. authorization: 'c56e30dc-2883-4270-a59e-b2f7bae969c6',
  364. 'Content-Type': 'application/json'
  365. }
  366. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement