|
| 1 | +// Initial References |
| 2 | +let result = document.getElementById("result"); |
| 3 | +let btn = document.getElementById("get-leap-years"); |
| 4 | + |
| 5 | +// Function calculate the leap year and send response to the user |
| 6 | +function leapYearCalc() { |
| 7 | + // Get values from the input fields |
| 8 | + // Number() converts string value to number |
| 9 | + let startYear = Number(document.getElementById("start-year").value); |
| 10 | + let endYear = Number(document.getElementById("end-year").value); |
| 11 | + |
| 12 | + // If both start and end year are invalid |
| 13 | + if ( |
| 14 | + (startYear < 1582 || startYear > 2999) && |
| 15 | + (endYear < 1582 || endYear > 2999) |
| 16 | + ) { |
| 17 | + result.innerHTML = `<b style="color: red;">The start year and end year should be greater than 1581 and less than 3000.</b>`; |
| 18 | + } |
| 19 | + |
| 20 | + // If start year is greater than end year |
| 21 | + else if (startYear > endYear) { |
| 22 | + result.innerHTML = `<b style="color: red;">End year should be greater than the start year.</b>`; |
| 23 | + } |
| 24 | + |
| 25 | + // If start year is invalid |
| 26 | + else if (startYear < 1582 || startYear > 2999) { |
| 27 | + result.innerHTML = `<b style="color: red;">The start year should be greater than 1581 and less than 3000.</b>`; |
| 28 | + } |
| 29 | + |
| 30 | + // If end year is invalid |
| 31 | + else if (endYear < 1582 || endYear > 2999) { |
| 32 | + result.innerHTML = `<b style="color: red;">The end year should be greater than 1581 and less than 3000.</b>`; |
| 33 | + } |
| 34 | + |
| 35 | + // If both start and end years are valid |
| 36 | + else { |
| 37 | + // Empty array to store the leap years |
| 38 | + let leapYears = []; |
| 39 | + for (let i = startYear; i <= endYear; i++) { |
| 40 | + // Determine if a year is a leap year |
| 41 | + // If true push it into leapYears[] |
| 42 | + |
| 43 | + if ((i % 4 == 0 && i % 100 != 0) || i % 400 == 0) { |
| 44 | + leapYears.push(i); |
| 45 | + } |
| 46 | + } |
| 47 | + // Display leap years in result div |
| 48 | + // toString() returns a string with comma seperated values |
| 49 | + // Use combo of split() and join() to replace ',' with ', ' |
| 50 | + result.innerHTML = `<b style="color: #f5c431;">There are ${leapYears.length |
| 51 | + } leap years between ${startYear} & ${endYear}.</b><span>${leapYears |
| 52 | + .toString() |
| 53 | + .split(",") |
| 54 | + .join(", ")}</span>`; |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +// Get Leap years when the button is clicked |
| 59 | +btn.addEventListener('click', leapYearCalc); |
| 60 | + |
| 61 | +// Get leap years when enter button is pressed |
| 62 | +document.addEventListener('keyup', (event) => { |
| 63 | + if (event.key === 'Enter') { |
| 64 | + leapYearCalc(); |
| 65 | + } |
| 66 | +}); |
0 commit comments