-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
82 lines (69 loc) · 2.77 KB
/
script.js
File metadata and controls
82 lines (69 loc) · 2.77 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
const apiKey = '4d82c4f1246aa4866c28aebe28486228';
const apiUrl = 'https://api.themoviedb.org/3/movie/now_playing';
async function fetchMovies() {
try {
const response = await fetch(`${apiUrl}?api_key=${apiKey}`);
const data = await response.json();
displayMovies(data.results);
} catch (error) {
console.error('Error fetching data:', error);
}
}
function displayMovies(movies) {
const movieGrid = document.querySelector('.movie-grid');
movieGrid.innerHTML = '';
movies.forEach(movie => {
const movieCard = document.createElement('div');
movieCard.classList.add('movie-card');
const movieImage = document.createElement('img');
movieImage.src = `https://image.tmdb.org/t/p/w500${movie.poster_path}`;
movieImage.alt = movie.title;
const movieTitle = document.createElement('h3');
movieTitle.textContent = movie.title;
const movieDescription = document.createElement('p');
movieDescription.textContent = `Rating: ${movie.vote_average}`;
const moreInfoButton = document.createElement('button');
moreInfoButton.classList.add('movie-button');
moreInfoButton.textContent = 'More Info';
moreInfoButton.addEventListener('click', () => {
alert(`Movie ID: ${movie.id}`);
});
movieCard.append(movieImage, movieTitle, movieDescription, moreInfoButton);
movieGrid.appendChild(movieCard);
});
}
async function submitMovieRating(movieId, rating) {
const options = {
method: 'POST',
headers: {
accept: 'application/json',
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify({ value: rating })
};
try {
const response = await fetch(`https://api.themoviedb.org/3/movie/${movieId}/rating?api_key=${apiKey}`, options);
const result = await response.json();
if (response.ok) {
alert('Rating submitted successfully!');
} else {
alert(`Failed to submit rating: ${result.status_message}`);
}
} catch (error) {
console.error('Error submitting rating:', error);
}
}
async function handleRatingSubmission(event) {
event.preventDefault();
const movieId = document.getElementById('movieId').value;
const rating = parseFloat(document.getElementById('rating').value);
if (movieId && rating >= 0.5 && rating <= 10) {
await submitMovieRating(movieId, rating);
} else {
alert('Please provide a valid movie ID and rating (between 0.5 and 10)!');
}
}
if (document.getElementById('ratingForm')) {
document.getElementById('ratingForm').addEventListener('submit', handleRatingSubmission);
}
window.addEventListener('DOMContentLoaded', fetchMovies);