-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
66 lines (52 loc) · 2.1 KB
/
script.js
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
const container = document.querySelector('.container');
const seats = document.querySelectorAll('.row .seat:not(.occupied)'); //creates array of dom elements
const count = document.getElementById('count');
const total = document.getElementById('total');
const movieSelect = document.getElementById('movie');
// poopulate data on browser reload
populateUi();
let ticketPrice = parseInt(movieSelect.value); // can also add + inplace of parseInt( )
//save selected movie index and price
function setMovieData(movieIndex, moviePrice) {
localStorage.setItem('selectedMovieIndex', movieIndex);
localStorage.setItem('selectedMoviePrice', moviePrice);
}
//updates movie ticket count and price
function updateSelectedCount() {
const selectedSeats = document.querySelectorAll('.row .seat.selected');
const selectedSeatsCount = selectedSeats.length;
const seatsIndex = [...selectedSeats].map(seat => [...seats].indexOf(seat));
localStorage.setItem('selectedSeats', JSON.stringify(seatsIndex));
count.innerText = selectedSeatsCount;
total.innerText = `$${selectedSeatsCount * ticketPrice}`;
}
// populate selected data after reloads browser
function populateUi() {
const selectedSeats = JSON.parse(localStorage.getItem('selectedSeats'));
if (selectedSeats !== null && selectedSeats.length > 0) {
seats.forEach((seat, index) => {
if (selectedSeats.indexOf(index) > -1) {
seat.classList.add('selected');
}
})
}
const selectedMovieIndex = localStorage.getItem('selectedMovieIndex');
if (selectedMovieIndex !== null) {
movieSelect.selectedIndex = selectedMovieIndex;
}
}
// seat click event listner
movieSelect.addEventListener('change', (event) => {
ticketPrice = +event.target.value;
setMovieData(event.target.selectedIndex, event.target.value);
updateSelectedCount();
})
// seat click event listner
container.addEventListener('click', (event) => {
if (event.target.classList.contains('seat') && !event.target.classList.contains('occupied')) {
event.target.classList.toggle('selected');
updateSelectedCount();
}
})
// intial count and total of movie
updateSelectedCount();