|
| 1 | +const searchBtn = document.getElementById('search-btn'); |
| 2 | +const searchInput = document.getElementById('search'); |
| 3 | +const movieContainer = document.getElementById('movie-container'); |
| 4 | + |
| 5 | +// API Details |
| 6 | +const API_KEY = '40bbd9b4'; // Replace with your OMDB or TMDB API key |
| 7 | +const API_URL = `https://www.omdbapi.com/?apikey=${API_KEY}&s=`; |
| 8 | + |
| 9 | +// Display Movies |
| 10 | +const displayMovies = (movies) => { |
| 11 | + movieContainer.innerHTML = ''; // Clear previous results |
| 12 | + |
| 13 | + movies.forEach((movie) => { |
| 14 | + const movieCard = document.createElement('div'); |
| 15 | + movieCard.classList.add('movie-card'); |
| 16 | + |
| 17 | + movieCard.innerHTML = ` |
| 18 | + <img src="${ |
| 19 | + movie.Poster !== 'N/A' ? movie.Poster : 'placeholder.jpg' |
| 20 | +}" alt="${movie.Title}"> |
| 21 | + <h3>${movie.Title}</h3> |
| 22 | + <p><strong>Year:</strong> ${movie.Year}</p> |
| 23 | + `; |
| 24 | + |
| 25 | + movieContainer.appendChild(movieCard); |
| 26 | + }); |
| 27 | +}; |
| 28 | + |
| 29 | +// Show Error Message |
| 30 | +const showError = (message) => { |
| 31 | + movieContainer.innerHTML = `<p class="error">${message}</p>`; |
| 32 | +}; |
| 33 | + |
| 34 | +// Fetch Movies |
| 35 | +async function fetchMovies(query) { |
| 36 | + try { |
| 37 | + const response = await fetch(`${API_URL}${query}`); |
| 38 | + const data = await response.json(); |
| 39 | + |
| 40 | + if (data.Response === 'True') { |
| 41 | + displayMovies(data.Search); |
| 42 | + } else { |
| 43 | + showError(data.Error); |
| 44 | + } |
| 45 | + } catch (error) { |
| 46 | + console.error('Error fetching data:', error); |
| 47 | + showError('Unable to fetch data. Please try again later.'); |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +// Event Listener |
| 52 | +searchBtn.addEventListener('click', () => { |
| 53 | + const query = searchInput.value.trim(); |
| 54 | + if (query) { |
| 55 | + fetchMovies(query); |
| 56 | + } else { |
| 57 | + showError('Please enter a movie name.'); |
| 58 | + } |
| 59 | +}); |
0 commit comments