Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 0349d0c

Browse files
Adding fetch
1 parent 30e67c1 commit 0349d0c

File tree

7 files changed

+174
-161
lines changed

7 files changed

+174
-161
lines changed

‎app/js/script.js

Lines changed: 81 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,15 @@ class Photo {
77
constructor(json){
88
Object.assign(this, json);
99
}
10-
showModal(){
10+
/* showModal(){
1111
Swal.fire({
1212
width: '50rem',
1313
imageUrl: this.src.original,
1414
imageWidth: '60%',
1515
showConfirmButton: false,
1616
imageAlt: this.alt
1717
});
18-
}
18+
} */
1919
}
2020

2121
// La API key que pedí a la API de Pexels.
@@ -45,112 +45,114 @@ const removeAllChild = (parent) => {
4545
}
4646
}
4747

48-
// Creamos una función que nos permita crear nuevos elementos (fotos) para la galería.
49-
const createNewGalleryItem = (photoObject) => {
50-
// Creamos un nuevo objeto 'Photo' a partir del objeto que nos dá el 'json'.
51-
const photo = new Photo(photoObject);
52-
// Creamos un nuevo elemento article.
53-
let newGalleryItem = document.createElement('article');
54-
// Le asignamos la clase que define los estilos que poseerán las fotos.
55-
newGalleryItem.classList.add('gallery__item');
56-
// Y le ponemos una etiqueta img con los datos del objeto para que se muestren.
57-
newGalleryItem.innerHTML = `<img src="${photo.src.large}" alt="${photo.alt}"></img>`;
58-
// Y por último le agregamos ese nuevo elemento a la galería. Utilicé el 'prepend' ya que quiero que se agregue al principio, para respetar el orden que simulo en el array.
59-
galleryContainer.prepend(newGalleryItem);
60-
// Retornamos el objeto 'Photo' para poder utilizarlo posteriormente.
61-
return photo;
48+
let pageIndex = 1;
49+
let searchValue;
50+
51+
const fetchPhotos = async (baseURL) => {
52+
const res = await fetch(baseURL, HEADERS);
53+
const data = await res.json();
54+
return data;
6255
}
6356

64-
/* const getNextPage = (next_page) => {
65-
if (next_page){
66-
loadMoreBtn.addEventListener('click', async () => {
67-
const data = await fetchPhotos(next_page);
68-
data.photos.map((photoObject) => {
69-
let photo = createNewGalleryItem(photoObject);
70-
let galleryItem = document.querySelector('article');
71-
galleryItem.addEventListener('click', () => photo.showModal());
72-
});
73-
});
57+
const validateSearchValue = (searchValue) => {
58+
if (searchValue.length < 3){
59+
// Avisamos el error.
60+
errorAlert.innerText = 'Debe introducir una palabra mayor a 3 letras.';
61+
// Creamos un timer que limpie el 'errorAlert' despues de 1.5 segundos.
62+
setTimeout(() => {
63+
errorAlert.innerText = '';
64+
}, 1500);
7465
}else{
75-
loadMoreBtn.style.display = 'none';
66+
returntrue;
7667
}
77-
} */
68+
}
69+
70+
const generateHTML = (data, photoType) => {
71+
data.photos.forEach((photoObject) => {
72+
const photo = new Photo(photoObject);
73+
// Creamos un nuevo elemento article.
74+
let newGalleryItem = document.createElement('article');
75+
// Le asignamos la clase que define los estilos que poseerán las fotos.
76+
newGalleryItem.classList.add('gallery__item');
77+
newGalleryItem.setAttribute('data-photo', photoType);
78+
// Y le ponemos una etiqueta img con los datos del objeto para que se muestren.
79+
newGalleryItem.innerHTML = `<img src="${photo.src.large}" alt="${photo.alt}"></img>`;
80+
// Y por último le agregamos ese nuevo elemento a la galería.
81+
galleryContainer.append(newGalleryItem);
82+
});
83+
}
7884

7985
// Creamos una función que nos devuelva las fotos a partir de lo ingresado por el usuario en la barra de búsqueda.
80-
const getSearchedPhotos = (searchValue) => {
81-
fetch(`https://api.pexels.com/v1/search?query=${searchValue}&per_page=16`, HEADERS)
82-
.then((res) => res.json())
83-
.then((data) => {
84-
removeAllChild(galleryContainer);
85-
data.photos.map((photoObject) => {
86-
let photo = createNewGalleryItem(photoObject);
87-
let galleryItem = document.querySelector('article');
88-
galleryItem.addEventListener('click', () => photo.showModal());
89-
});
90-
});
91-
/* getNextPage(data.next_page); */
86+
const getSearchedPhotos = async (e) => {
87+
e.preventDefault();
88+
searchValue = e.target.querySelector('input').value;
89+
if (validateSearchValue(searchValue) === true){
90+
const data = await fetchPhotos(`https://api.pexels.com/v1/search?query=${searchValue}&per_page=16`);
91+
if (!data.next_page){
92+
loadMoreBtn.style.display = 'none'
93+
}
94+
removeAllChild(galleryContainer);
95+
generateHTML(data, 'search');
96+
}
97+
}
98+
99+
const getMoreSearchedPhotos = async (index) => {
100+
const data = await fetchPhotos(`https://api.pexels.com/v1/search?query=${searchValue}&per_page=16&page=${index}`);
101+
if (!data.next_page){
102+
loadMoreBtn.style.display = 'none'
103+
}
104+
generateHTML(data, 'search');
92105
}
93106

94107
// Creamos una función que nos devuelva fotos aleatorias.
95-
const getInitialRandomPhotos = () => {
96-
fetch(`https://api.pexels.com/v1/curated?page=1&per_page=16`, HEADERS)
97-
.then((res) => res.json())
98-
.then((data) => {
99-
console.log(data)
100-
data.photos.map((photoObject) => {
101-
let photo = createNewGalleryItem(photoObject);
102-
let galleryItem = document.querySelector('article');
103-
galleryItem.addEventListener('click', () => photo.showModal());
104-
});
105-
});
106-
/* getNextPage(data.next_page); */
108+
const getInitialRandomPhotos = async (index) => {
109+
const data = await fetchPhotos(`https://api.pexels.com/v1/curated?per_page=16&page=${index}`);
110+
if (!data.next_page){
111+
loadMoreBtn.style.display = 'none'
112+
}
113+
generateHTML(data, 'curated');
107114
}
108115

109-
// Creamos una función que nos permita tomar lo que el usuario ingresa en la barra de búsqueda y fijarnos si matchea con alguna de las fotos que tenemos guardadas en el array (simulador de base de datos).
110-
const getSearcheInputValue = (e) => {
111-
// Evitamos el funcionamiento por defualt del evento submit.
112-
e.preventDefault();
113-
// Tomamos al input del form y lo almacenamos.
114-
let inputSearch = e.target.querySelector('input');
115-
// Y también guardamos el value en otra.
116-
const userSearch = inputSearch.value;
117-
// Validamos el value del input.
118-
if (userSearch.length > 3){
119-
// Llamamos a la función que filtra.
120-
getSearchedPhotos(userSearch);
121-
errorAlert.innerText = '';
122-
} else{
123-
// Sino, avisamos el error.
124-
errorAlert.innerText = 'Debe introducir una palabra mayor a 3 letras.';
125-
// Creamos un timer que limpie el 'errorAlert' despues de 1.5 segundos.
126-
setTimeout(() => {
127-
errorAlert.innerText = '';
128-
}, 1500);
116+
const loadMorePhotos = () => {
117+
let index = ++pageIndex;
118+
let galleryItem = document.querySelector('article');
119+
let dataPhoto = galleryItem.getAttribute('data-photo')
120+
if (dataPhoto == 'curated'){
121+
getInitialRandomPhotos(index);
122+
}else{
123+
getMoreSearchedPhotos(index);
129124
}
130125
}
131126

132-
// Evento submit del form, donde se llama a una función que trae las fotos a partir de la búsqueda.
133-
searchForm.addEventListener('submit', (e) => getSearcheInputValue(e));
134127

128+
/**** EVENTOS ****/
129+
130+
// Evento submit del form, donde se llama a una función que trae las fotos a partir de la búsqueda.
131+
searchForm.addEventListener('submit', (e) => getSearchedPhotos(e));
132+
loadMoreBtn.addEventListener('click', () => loadMorePhotos());
135133
// Cuando se carge la ventana, llamamos a la función que nos carga 8 fotos simulando que son fotos aleatorias.
136-
document.addEventListener('DOMContentLoaded', getInitialRandomPhotos());
134+
document.addEventListener('DOMContentLoaded', getInitialRandomPhotos(pageIndex));
137135

138136
// Botón para limpiar el input del form.
139137
clearInputButton.addEventListener('click', () => {
138+
let pageIndex = 1;
140139
// Limpiamos el input.
141140
document.getElementById('searchInput').value = '';
142141
// Cuando la galería tiene 3 hijos es porque no se tuvo que crear el h2 para error. Sino, si se tuvo que crear el h2 por lo que tiene más hijos.
143-
if (gallery.childNodes.length == 3){
142+
/* if (gallery.childNodes.length == 3){
144143
// Borra los hijos del contenedor de la galería.
145144
removeAllChild(galleryContainer);
146145
// Carga las fotos aleatorias del principio.
147-
getInitialRandomPhotos();
146+
getInitialRandomPhotos(pageIndex);
148147
}else{
149148
// Borra el h2 con el error.
150149
gallery.childNodes[1].remove();
151150
// Carga las fotos aleatorias del principio.
152-
getInitialRandomPhotos();
153-
}
151+
getInitialRandomPhotos(pageIndex);
152+
} */
153+
removeAllChild(galleryContainer);
154+
getInitialRandomPhotos(pageIndex);
155+
loadMoreBtn.style.display = 'flex';
154156
});
155157

156158

‎app/scss/components/gallery.scss

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,12 +74,19 @@
7474
border: 1px solid var(--clr-text-gallery);
7575
border-radius: 50%;
7676
text-decoration: none;
77+
transition: all .4s ease;
7778

7879
&:hover{
7980
cursor: pointer;
81+
border: 1px solid var(--clr-text-gallery-2);
82+
83+
i{
84+
color: var(--clr-text-gallery-2);
85+
}
8086
}
8187

8288
i{
89+
transition: all .4s ease;
8390
color: var(--clr-text-gallery);
8491
}
8592
}

‎app/scss/util/theme.scss

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
--clr-bg-gallery: #414141;
1414
--clr-text-gallery: #b8c8c8;
1515
--clr-h2-gallery: #102028;
16+
--clr-text-gallery-2: #182830;
1617
// Footer
1718
--clr-bg-footer: #102028;
1819
--clr-bg-footer-2: #182830;
@@ -34,6 +35,7 @@
3435
--clr-bg-gallery: #121212;
3536
--clr-text-gallery: #b8c8c8;
3637
--clr-h2-gallery: #b8c8c8;
38+
--clr-text-gallery-2: #e8e8e8;
3739
// Footer
3840
--clr-bg-footer: #17191f;
3941
--clr-bg-footer-2: #1a1c22;

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /