-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
85 lines (71 loc) · 2.55 KB
/
Copy pathscript.js
File metadata and controls
85 lines (71 loc) · 2.55 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
const apiKey = 'GBUghdHlZ_gnLezb';
const apiUrl = `https://movieapi-v2ft.onrender.com/api/movies`;
const searchApiUrl = `https://movieapi-v2ft.onrender.com/api/search/`;
const movieGallery = document.getElementById('movie-gallery');
const errorMessage = document.getElementById('error-message');
const searchInput = document.getElementById('search-input');
// Fetch all movies initially
fetchMovies(apiUrl);
// Event listener for input changes in the search input
searchInput.addEventListener('input', () => {
const movieName = searchInput.value.trim();
if (movieName) {
// Fetch movies based on search input
fetchMovies(`${searchApiUrl}${movieName}`);
} else {
// Fetch all movies if search input is empty
fetchMovies(apiUrl);
}
});
async function fetchMovies(url) {
try {
const response = await fetch(url, {
method: 'GET',
headers: {
'x-api-key': apiKey
}
});
if (!response.ok) {
throw new Error('Network response was not ok');
}
const movies = await response.json();
displayMovies(movies);
} catch (error) {
console.error('Error fetching movies:', error);
showError('Error loading movies. Please try again later.');
}
}
function displayMovies(movies) {
if (!Array.isArray(movies) || movies.length === 0) {
showError('No movies found.');
return;
}
// Sort movies by year in descending order (latest first)
movies.sort((a, b) => {
return parseInt(b.year) - parseInt(a.year);
});
movieGallery.innerHTML = ''; // Clear previous movies
movies.forEach(movie => {
const movieCard = document.createElement('div');
movieCard.classList.add('movie-card');
// Start building the movie card content
movieCard.innerHTML = `
<img src="${movie.poster}" alt="${movie.title}">
<div class="movie-info">
<h3>${movie.title}</h3>
`;
// Conditionally append year if available
if (movie.year) {
movieCard.innerHTML += `<h3 class="year">${movie.year}</h3>`;
}
// Close the movie info div
movieCard.innerHTML += `</div>`;
movieGallery.appendChild(movieCard);
});
}
function showError(message) {
errorMessage.innerText = message;
errorMessage.style.display = 'block';
}
// Call the function to fetch movies on page load
fetchMovies(apiUrl);