1+ // Tip Calculator Logic
2+
3+ const billInput = document . getElementById ( 'bill' ) ;
4+ const tipButtons = document . querySelectorAll ( '.tip-btn' ) ;
5+ const customTipInput = document . getElementById ( 'customTip' ) ;
6+ const splitInput = document . getElementById ( 'split' ) ;
7+ const tipDisplay = document . getElementById ( 'tip' ) ;
8+ const totalDisplay = document . getElementById ( 'total' ) ;
9+ const eachDisplay = document . getElementById ( 'each' ) ;
10+ const resultsDiv = document . getElementById ( 'results' ) ;
11+
12+ let selectedTip = 10 ;
13+
14+ // Event listeners for tip buttons
15+ tipButtons . forEach ( btn => {
16+ btn . addEventListener ( 'click' , ( ) => {
17+ tipButtons . forEach ( b => b . classList . remove ( 'active' ) ) ;
18+ btn . classList . add ( 'active' ) ;
19+ selectedTip = parseFloat ( btn . dataset . tip ) ;
20+ customTipInput . value = '' ;
21+ calculate ( ) ;
22+ } ) ;
23+ } ) ;
24+
25+ // Custom tip input
26+ customTipInput . addEventListener ( 'input' , ( ) => {
27+ tipButtons . forEach ( b => b . classList . remove ( 'active' ) ) ;
28+ selectedTip = parseFloat ( customTipInput . value ) || 0 ;
29+ calculate ( ) ;
30+ } ) ;
31+
32+ // Bill, split inputs
33+ billInput . addEventListener ( 'input' , calculate ) ;
34+ splitInput . addEventListener ( 'input' , calculate ) ;
35+
36+ function calculate ( ) {
37+ const bill = parseFloat ( billInput . value ) ;
38+ const people = Math . max ( 1 , parseInt ( splitInput . value , 10 ) || 1 ) ;
39+
40+ if ( isNaN ( bill ) || bill <= 0 || isNaN ( selectedTip ) || selectedTip < 0 ) {
41+ tipDisplay . textContent = "0.00" ;
42+ totalDisplay . textContent = "0.00" ;
43+ eachDisplay . textContent = "0.00" ;
44+ resultsDiv . style . background = '#fee2e2' ;
45+ return ;
46+ }
47+
48+ const tip = bill * selectedTip / 100 ;
49+ const total = bill + tip ;
50+ const each = total / people ;
51+
52+ tipDisplay . textContent = tip . toFixed ( 2 ) ;
53+ totalDisplay . textContent = total . toFixed ( 2 ) ;
54+ eachDisplay . textContent = each . toFixed ( 2 ) ;
55+
56+ resultsDiv . style . background = '#f1f5f9' ;
57+ }
58+
59+ // Initial calculation on load
60+ calculate ( ) ;
0 commit comments