<!-- Simple Accordion Component in TypeScript --> <div id="accordion"> <button class="accordion-button" id="accBtn">Toggle Content</button> <div class="accordion-content" id="accContent" style="display:none;"> <p>This content is hidden by default and shown when the button is clicked.</p> </div> </div> <script type="text/typescript"> // Get references to button and content div const accordionButton = document.getElementById('accBtn') as HTMLButtonElement; const accordionContent = document.getElementById('accContent') as HTMLDivElement; // Function to toggle the accordion content visibility function toggleAccordion() { if (accordionContent.style.display === 'none') { accordionContent.style.display = 'block'; // Show content accordionButton.textContent = 'Hide Content'; // Change button text } else { accordionContent.style.display = 'none'; // Hide content accordionButton.textContent = 'Toggle Content'; // Reset button text } } // Attach event listener to button click accordionButton.addEventListener('click', toggleAccordion); </script>
<!-- A simple counter implemented in TypeScript --> <div> <button id="decrement">-</button> <span id="counterValue">0</span> <button id="increment">+</button> </div> <script type="text/typescript"> // Select the buttons and the counter display span const decrementButton = document.getElementById('decrement') as HTMLButtonElement; const incrementButton = document.getElementById('increment') as HTMLButtonElement; const counterDisplay = document.getElementById('counterValue') as HTMLSpanElement; // Initialize counter value let counter = 0; // Function to update the display with the current counter value function updateDisplay() { counterDisplay.textContent = counter.toString(); } // Increment function increases counter by 1 function increment() { counter++; updateDisplay(); } // Decrement function decreases counter by 1 function decrement() { counter--; updateDisplay(); } // Attach event listeners to buttons incrementButton.addEventListener('click', increment); decrementButton.addEventListener('click', decrement); </script>
<!-- Simple To-Do List implemented in TypeScript --> <div> <input type="text" id="todoInput" placeholder="Add a new task..." /> <button id="addTask">Add Task</button> <ul id="taskList"></ul> </div> <script type="text/typescript"> // Get references to input, button, and list const input = document.getElementById('todoInput') as HTMLInputElement; const addButton = document.getElementById('addTask') as HTMLButtonElement; const taskList = document.getElementById('taskList') as HTMLUListElement; // Function to add a new task function addTask() { const taskText = input.value.trim(); if (taskText === '') return; // Ignore empty tasks // Create a new list item const li = document.createElement('li'); li.textContent = taskText; // Add a remove button for the task const removeBtn = document.createElement('button'); removeBtn.textContent = 'Remove'; removeBtn.style.marginLeft = '10px'; // Remove task when remove button clicked removeBtn.addEventListener('click', () => { taskList.removeChild(li); }); li.appendChild(removeBtn); taskList.appendChild(li); // Clear input after adding task input.value = ''; } // Attach event listener to add button addButton.addEventListener('click', addTask); </script>
<!-- Basic Calculator implemented in TypeScript --> <div> <input type="number" id="num1" placeholder="Number 1" /> <input type="number" id="num2" placeholder="Number 2" /> <select id="operator"> <option value="+">+</option> <option value="-">-</option> <option value="*">*</option> <option value="/">/</option> </select> <button id="calculate">Calculate</button> <div id="result"></div> </div> <script type="text/typescript"> // Get references to inputs and result div const num1 = document.getElementById('num1') as HTMLInputElement; const num2 = document.getElementById('num2') as HTMLInputElement; const operator = document.getElementById('operator') as HTMLSelectElement; const calculateBtn = document.getElementById('calculate') as HTMLButtonElement; const resultDiv = document.getElementById('result') as HTMLDivElement; // Function to perform calculation function calculate() { const n1 = parseFloat(num1.value); const n2 = parseFloat(num2.value); let result: number | string = ''; if (isNaN(n1) || isNaN(n2)) { result = 'Please enter valid numbers.'; } else { switch (operator.value) { case '+': result = n1 + n2; break; case '-': result = n1 - n2; break; case '*': result = n1 * n2; break; case '/': result = n2 !== 0 ? n1 / n2 : 'Cannot divide by zero'; break; default: result = 'Invalid operator'; } } resultDiv.textContent = result.toString(); } // Attach event listener to calculate button calculateBtn.addEventListener('click', calculate); </script>
<!-- Check if input string is a palindrome --> <div> <input type="text" id="palindromeInput" placeholder="Enter text" /> <button id="checkPalindrome">Check</button> <div id="palindromeResult"></div> </div> <script type="text/typescript"> // Get input and result elements const palindromeInput = document.getElementById('palindromeInput') as HTMLInputElement; const checkBtn = document.getElementById('checkPalindrome') as HTMLButtonElement; const resultDiv = document.getElementById('palindromeResult') as HTMLDivElement; // Function to check palindrome function isPalindrome(str: string): boolean { const cleaned = str.toLowerCase().replace(/[^a-z0-9]/g, ''); const reversed = cleaned.split('').reverse().join(''); return cleaned === reversed; } // Event handler for button click checkBtn.addEventListener('click', () => { const text = palindromeInput.value; if (text.trim() === '') { resultDiv.textContent = 'Please enter some text.'; } else { const result = isPalindrome(text); resultDiv.textContent = result ? 'It is a palindrome!' : 'Not a palindrome.'; } }); </script>
<!-- Generate Fibonacci sequence up to a limit --> <div> <input type="number" id="fibLimit" placeholder="Enter limit" /> <button id="generateFib">Generate</button> <div id="fibResult"></div> </div> <script type="text/typescript"> // Get input and result container const fibLimit = document.getElementById('fibLimit') as HTMLInputElement; const generateBtn = document.getElementById('generateFib') as HTMLButtonElement; const fibResult = document.getElementById('fibResult') as HTMLDivElement; // Function to generate Fibonacci numbers up to limit function generateFibonacci(limit: number): number[] { const fibs = [0, 1]; while (fibs[fibs.length - 1] <= limit) { fibs.push(fibs[fibs.length - 1] + fibs[fibs.length - 2]); } return fibs.slice(0, -1); } // Event handler for button click generateBtn.addEventListener('click', () => { const limit = parseInt(fibLimit.value); if (isNaN(limit) || limit < 0) { fibResult.textContent = 'Please enter a positive number.'; return; } const sequence = generateFibonacci(limit); fibResult.textContent = sequence.join(', '); }); </script>
<!-- Convert Celsius to Fahrenheit and vice versa --> <div> <input type="number" id="tempInput" placeholder="Enter temperature" /> <select id="scale"> <option value="CtoF">Celsius to Fahrenheit</option> <option value="FtoC">Fahrenheit to Celsius</option> </select> <button id="convertTemp">Convert</button> <div id="tempResult"></div> </div> <script type="text/typescript"> // Get elements const tempInput = document.getElementById('tempInput') as HTMLInputElement; const scaleSelect = document.getElementById('scale') as HTMLSelectElement; const convertBtn = document.getElementById('convertTemp') as HTMLButtonElement; const tempResult = document.getElementById('tempResult') as HTMLDivElement; // Function to convert temperature function convertTemperature(value: number, scale: string): number { if (scale === 'CtoF') { return value * 9 / 5 + 32; } else { return (value - 32) * 5 / 9; } } // Button event listener convertBtn.addEventListener('click', () => { const temp = parseFloat(tempInput.value); if (isNaN(temp)) { tempResult.textContent = 'Please enter a valid temperature.'; return; } const scale = scaleSelect.value; const converted = convertTemperature(temp, scale); tempResult.textContent = `Converted temperature: ${converted.toFixed(2)}`; }); </script>
<!-- Generate a random quote from a predefined list --> <div> <button id="generateQuote">Get Quote</button> <div id="quoteDisplay"></div> </div> <script type="text/typescript"> // Quotes array const quotes: string[] = [ "The best way to get started is to quit talking and begin doing.", "Don't let yesterday take up too much of today.", "It's not whether you get knocked down, it's whether you get up.", "If you are working on something exciting, it will keep you motivated." ]; // Elements const generateBtn = document.getElementById('generateQuote') as HTMLButtonElement; const quoteDisplay = document.getElementById('quoteDisplay') as HTMLDivElement; // Generate random quote generateBtn.addEventListener('click', () => { const randomIndex = Math.floor(Math.random() * quotes.length); quoteDisplay.textContent = quotes[randomIndex]; }); </script>
<!-- Stopwatch with start, stop, and reset buttons --> <div> <div id="display">00:00:00</div> <button id="start">Start</button> <button id="stop">Stop</button> <button id="reset">Reset</button> </div> <script type="text/typescript"> // Elements const display = document.getElementById('display') as HTMLDivElement; const startBtn = document.getElementById('start') as HTMLButtonElement; const stopBtn = document.getElementById('stop') as HTMLButtonElement; const resetBtn = document.getElementById('reset') as HTMLButtonElement; let timer: number | null = null; let seconds = 0; // Format time as hh:mm:ss function formatTime(sec: number): string { const hrs = Math.floor(sec / 3600); const mins = Math.floor((sec % 3600) / 60); const secs = sec % 60; return `${hrs.toString().padStart(2,'0')}:${mins.toString().padStart(2,'0')}:${secs.toString().padStart(2,'0')}`; } // Start timer startBtn.addEventListener('click', () => { if (timer !== null) return; // Already running timer = setInterval(() => { seconds++; display.textContent = formatTime(seconds); }, 1000); }); // Stop timer stopBtn.addEventListener('click', () => { if (timer !== null) { clearInterval(timer); timer = null; } }); // Reset timer resetBtn.addEventListener('click', () => { if (timer !== null) { clearInterval(timer); timer = null; } seconds = 0; display.textContent = '00:00:00'; }); </script>
<!-- Calculate Body Mass Index (BMI) --> <div> <input type="number" id="weight" placeholder="Weight in kg" /> <input type="number" id="height" placeholder="Height in meters" /> <button id="calculateBMI">Calculate BMI</button> <div id="bmiResult"></div> </div> <script type="text/typescript"> // Elements const weightInput = document.getElementById('weight') as HTMLInputElement; const heightInput = document.getElementById('height') as HTMLInputElement; const calculateBMIButton = document.getElementById('calculateBMI') as HTMLButtonElement; const bmiResult = document.getElementById('bmiResult') as HTMLDivElement; // Function to calculate BMI function calculateBMI(weight: number, height: number): number { return weight / (height * height); } // Button click handler calculateBMIButton.addEventListener('click', () => { const weight = parseFloat(weightInput.value); const height = parseFloat(heightInput.value); if (isNaN(weight) || isNaN(height) || height === 0) { bmiResult.textContent = 'Please enter valid weight and height.'; return; } const bmi = calculateBMI(weight, height); bmiResult.textContent = `Your BMI is ${bmi.toFixed(2)}`; }); </script>
<!-- Simple To-Do list with add and delete functionality --> <div> <input type="text" id="todoInput" placeholder="Enter new task" /> <button id="addTodo">Add Task</button> <ul id="todoList"></ul> </div> <script type="text/typescript"> // Elements const todoInput = document.getElementById('todoInput') as HTMLInputElement; const addTodoBtn = document.getElementById('addTodo') as HTMLButtonElement; const todoList = document.getElementById('todoList') as HTMLUListElement; // Add task function addTodoBtn.addEventListener('click', () => { const task = todoInput.value.trim(); if (!task) { alert('Please enter a task.'); return; } // Create list item const li = document.createElement('li'); li.textContent = task; // Create delete button const delBtn = document.createElement('button'); delBtn.textContent = 'Delete'; delBtn.style.marginLeft = '10px'; // Delete task on click delBtn.addEventListener('click', () => { todoList.removeChild(li); }); li.appendChild(delBtn); todoList.appendChild(li); todoInput.value = ''; }); </script>
<!-- Multiple choice quiz with score display --> <div> <div id="question"></div> <div id="options"></div> <button id="nextBtn">Next</button> <div id="result"></div> </div> <script type="text/typescript"> // Quiz questions array const quiz = [ { question: 'What is 2 + 2?', options: ['3', '4', '5'], answer: 1 }, { question: 'Capital of France?', options: ['Berlin', 'Paris', 'Madrid'], answer: 1 }, { question: 'Color of the sky?', options: ['Blue', 'Green', 'Red'], answer: 0 } ]; const questionEl = document.getElementById('question') as HTMLDivElement; const optionsEl = document.getElementById('options') as HTMLDivElement; const nextBtn = document.getElementById('nextBtn') as HTMLButtonElement; const resultEl = document.getElementById('result') as HTMLDivElement; let currentIndex = 0; let score = 0; // Show question and options function showQuestion() { const q = quiz[currentIndex]; questionEl.textContent = q.question; optionsEl.innerHTML = ''; q.options.forEach((opt, index) => { const button = document.createElement('button'); button.textContent = opt; button.addEventListener('click', () => { if (index === q.answer) score++; nextBtn.disabled = false; Array.from(optionsEl.children).forEach(btn => (btn as HTMLButtonElement).disabled = true); }); optionsEl.appendChild(button); }); nextBtn.disabled = true; } // Next question or show result nextBtn.addEventListener('click', () => { currentIndex++; if (currentIndex >= quiz.length) { questionEl.textContent = 'Quiz Complete!'; optionsEl.innerHTML = ''; nextBtn.style.display = 'none'; resultEl.textContent = `Your score is ${score} out of ${quiz.length}`; } else { showQuestion(); } }); showQuestion(); </script>
<!-- Simple manual image slider --> <div> <img id="sliderImage" src="https://via.placeholder.com/400x200?text=Image+1" alt="Slider Image" width="400" height="200" /><br> <button id="prevBtn">Previous</button> <button id="nextBtn">Next</button> </div> <script type="text/typescript"> // Images array const images = [ 'https://via.placeholder.com/400x200?text=Image+1', 'https://via.placeholder.com/400x200?text=Image+2', 'https://via.placeholder.com/400x200?text=Image+3' ]; const sliderImage = document.getElementById('sliderImage') as HTMLImageElement; const prevBtn = document.getElementById('prevBtn') as HTMLButtonElement; const nextBtn = document.getElementById('nextBtn') as HTMLButtonElement; let currentIndex = 0; // Show image at current index function showImage(index: number) { sliderImage.src = images[index]; } // Previous button click prevBtn.addEventListener('click', () => { currentIndex = (currentIndex - 1 + images.length) % images.length; showImage(currentIndex); }); // Next button click nextBtn.addEventListener('click', () => { currentIndex = (currentIndex + 1) % images.length; showImage(currentIndex); }); </script>
<!-- Countdown from 10 to 0 --> <div> <div id="countdown">10</div> <button id="startCountdown">Start Countdown</button> </div> <script type="text/typescript"> // Elements const countdownEl = document.getElementById('countdown') as HTMLDivElement; const startBtn = document.getElementById('startCountdown') as HTMLButtonElement; let timer: number | null = null; let timeLeft = 10; // Start countdown on button click startBtn.addEventListener('click', () => { if (timer !== null) return; // Already running timeLeft = 10; countdownEl.textContent = timeLeft.toString(); timer = setInterval(() => { timeLeft--; countdownEl.textContent = timeLeft.toString(); if (timeLeft <= 0) { clearInterval(timer!); timer = null; alert('Time is up!'); } }, 1000); }); </script>
<!-- Convert USD to EUR and vice versa --> <div> <input type="number" id="amount" placeholder="Enter amount" /> <select id="currency"> <option value="USDtoEUR">USD to EUR</option> <option value="EURtoUSD">EUR to USD</option> </select> <button id="convertCurrency">Convert</button> <div id="currencyResult"></div> </div> <script type="text/typescript"> // Elements const amountInput = document.getElementById('amount') as HTMLInputElement; const currencySelect = document.getElementById('currency') as HTMLSelectElement; const convertCurrencyBtn = document.getElementById('convertCurrency') as HTMLButtonElement; const currencyResult = document.getElementById('currencyResult') as HTMLDivElement; // Exchange rate (example) const exchangeRate = 0.85; // 1 USD = 0.85 EUR // Conversion function function convertCurrency(amount: number, conversion: string): number { if (conversion === 'USDtoEUR') { return amount * exchangeRate; } else { return amount / exchangeRate; } } // Button event convertCurrencyBtn.addEventListener('click', () => { const amount = parseFloat(amountInput.value); if (isNaN(amount)) { currencyResult.textContent = 'Please enter a valid amount.'; return; } const conversion = currencySelect.value; const result = convertCurrency(amount, conversion); currencyResult.textContent = `Converted amount: ${result.toFixed(2)}`; }); </script>
<!-- Validate contact form fields before submission --> <form id="contactForm"> <input type="text" id="name" placeholder="Your Name" /><br> <input type="email" id="email" placeholder="Your Email" /><br> <textarea id="message" placeholder="Your Message"></textarea><br> <button type="submit">Submit</button> </form> <div id="formResult"></div> <script type="text/typescript"> // Elements const contactForm = document.getElementById('contactForm') as HTMLFormElement; const nameInput = document.getElementById('name') as HTMLInputElement; const emailInput = document.getElementById('email') as HTMLInputElement; const messageInput = document.getElementById('message') as HTMLTextAreaElement; const formResult = document.getElementById('formResult') as HTMLDivElement; // Form submit event contactForm.addEventListener('submit', (event) => { event.preventDefault(); // Basic validation if (!nameInput.value.trim()) { formResult.textContent = 'Please enter your name.'; return; } if (!emailInput.value.trim() || !emailInput.value.includes('@')) { formResult.textContent = 'Please enter a valid email.'; return; } if (!messageInput.value.trim()) { formResult.textContent = 'Please enter a message.'; return; } formResult.textContent = 'Form submitted successfully!'; contactForm.reset(); }); </script>
<!-- Pick a color and show its hex code --> <input type="color" id="colorPicker" /><br> <div id="colorCode">#000000</div> <script type="text/typescript"> // Elements const colorPicker = document.getElementById('colorPicker') as HTMLInputElement; const colorCode = document.getElementById('colorCode') as HTMLDivElement; // Show initial color code colorCode.textContent = colorPicker.value; // Update color code when user picks a color colorPicker.addEventListener('input', () => { colorCode.textContent = colorPicker.value; }); </script>
<!-- Calculate BMI based on height and weight --> <input type="number" id="weight" placeholder="Weight (kg)" /><br> <input type="number" id="height" placeholder="Height (cm)" /><br> <button id="calculateBMI">Calculate BMI</button><br> <div id="bmiResult"></div> <script type="text/typescript"> // Elements const weightInput = document.getElementById('weight') as HTMLInputElement; const heightInput = document.getElementById('height') as HTMLInputElement; const calculateBtn = document.getElementById('calculateBMI') as HTMLButtonElement; const bmiResult = document.getElementById('bmiResult') as HTMLDivElement; // Calculate BMI formula: BMI = weight(kg) / (height(m))^2 calculateBtn.addEventListener('click', () => { const weight = parseFloat(weightInput.value); const heightCm = parseFloat(heightInput.value); if (isNaN(weight) || isNaN(heightCm) || weight <= 0 || heightCm <= 0) { bmiResult.textContent = 'Please enter valid positive numbers.'; return; } const heightM = heightCm / 100; const bmi = weight / (heightM * heightM); bmiResult.textContent = `Your BMI is ${bmi.toFixed(2)}`; }); </script>
<!-- Check strength of password input --> <input type="password" id="passwordInput" placeholder="Enter password" /><br> <div id="strengthResult"></div> <script type="text/typescript"> // Elements const passwordInput = document.getElementById('passwordInput') as HTMLInputElement; const strengthResult = document.getElementById('strengthResult') as HTMLDivElement; // Function to check password strength function checkStrength(password: string): string { let strength = 0; if (password.length >= 8) strength++; if (/[A-Z]/.test(password)) strength++; if (/[0-9]/.test(password)) strength++; if (/[\W]/.test(password)) strength++; switch (strength) { case 4: return 'Very Strong'; case 3: return 'Strong'; case 2: return 'Medium'; case 1: return 'Weak'; default: return 'Very Weak'; } } // Update strength on input passwordInput.addEventListener('input', () => { const strength = checkStrength(passwordInput.value); strengthResult.textContent = `Strength: ${strength}`; }); </script>
<!-- Fetch weather for a city using OpenWeather API --> <input type="text" id="cityInput" placeholder="Enter city" /><br> <button id="fetchWeather">Get Weather</button><br> <div id="weatherResult"></div> <script type="text/typescript"> // Elements const cityInput = document.getElementById('cityInput') as HTMLInputElement; const fetchWeatherBtn = document.getElementById('fetchWeather') as HTMLButtonElement; const weatherResult = document.getElementById('weatherResult') as HTMLDivElement; // Replace with your own OpenWeatherMap API key const API_KEY = 'YOUR_API_KEY_HERE'; // Fetch weather on button click fetchWeatherBtn.addEventListener('click', async () => { const city = cityInput.value.trim(); if (!city) { weatherResult.textContent = 'Please enter a city name.'; return; } try { const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${encodeURIComponent(city)}&appid=${API_KEY}&units=metric`); if (!response.ok) throw new Error('City not found'); const data = await response.json(); weatherResult.innerHTML = ` <p>Weather in ${data.name}: ${data.weather[0].description}</p> <p>Temperature: ${data.main.temp} °C</p> <p>Humidity: ${data.main.humidity} %</p> `; } catch (error) { weatherResult.textContent = error.message; } }); </script>
<!-- Show current time updating every second --> <div id="clock"></div> <script type="text/typescript"> // Element const clock = document.getElementById('clock') as HTMLDivElement; // Update clock every second function updateClock() { const now = new Date(); const timeStr = now.toLocaleTimeString(); clock.textContent = timeStr; } // Start clock interval setInterval(updateClock, 1000); updateClock(); // Initial call </script>
<!-- Calculate tip based on bill and tip percentage --> <input type="number" id="billAmount" placeholder="Bill amount" /><br> <input type="number" id="tipPercent" placeholder="Tip %" /><br> <button id="calculateTip">Calculate Tip</button><br> <div id="tipResult"></div> <script type="text/typescript"> // Elements const billAmount = document.getElementById('billAmount') as HTMLInputElement; const tipPercent = document.getElementById('tipPercent') as HTMLInputElement; const calculateTipBtn = document.getElementById('calculateTip') as HTMLButtonElement; const tipResult = document.getElementById('tipResult') as HTMLDivElement; // Calculate tip on button click calculateTipBtn.addEventListener('click', () => { const bill = parseFloat(billAmount.value); const tip = parseFloat(tipPercent.value); if (isNaN(bill) || isNaN(tip) || bill <= 0 || tip < 0) { tipResult.textContent = 'Please enter valid bill amount and tip percentage.'; return; } const tipValue = bill * (tip / 100); const total = bill + tipValue; tipResult.textContent = `Tip: $${tipValue.toFixed(2)}, Total: $${total.toFixed(2)}`; }); </script>
<!-- Add tasks and list them dynamically --> <input type="text" id="taskInput" placeholder="Enter task" /><br> <button id="addTask">Add Task</button><br> <ul id="taskList"></ul> <script type="text/typescript"> // Elements const taskInput = document.getElementById('taskInput') as HTMLInputElement; const addTaskBtn = document.getElementById('addTask') as HTMLButtonElement; const taskList = document.getElementById('taskList') as HTMLUListElement; // Add task on button click addTaskBtn.addEventListener('click', () => { const task = taskInput.value.trim(); if (!task) return; const li = document.createElement('li'); li.textContent = task; taskList.appendChild(li); taskInput.value = ''; }); </script>
<!-- Countdown from specified seconds --> <input type="number" id="secondsInput" placeholder="Seconds" /><br> <button id="startCountdown">Start Countdown</button><br> <div id="countdownDisplay"></div> <script type="text/typescript"> // Elements const secondsInput = document.getElementById('secondsInput') as HTMLInputElement; const startCountdownBtn = document.getElementById('startCountdown') as HTMLButtonElement; const countdownDisplay = document.getElementById('countdownDisplay') as HTMLDivElement; let countdownInterval: number | undefined; // Start countdown on button click startCountdownBtn.addEventListener('click', () => { let seconds = parseInt(secondsInput.value); if (isNaN(seconds) || seconds <= 0) { countdownDisplay.textContent = 'Enter a positive number.'; return; } // Clear existing countdown if any if (countdownInterval) { clearInterval(countdownInterval); } countdownDisplay.textContent = seconds.toString(); countdownInterval = setInterval(() => { seconds--; if (seconds <= 0) { countdownDisplay.textContent = 'Time\'s up!'; clearInterval(countdownInterval); return; } countdownDisplay.textContent = seconds.toString(); }, 1000); }); </script>
<!-- Simple image slider with next/prev buttons --> <img id="sliderImage" src="https://via.placeholder.com/400x200?text=1" alt="slider" width="400" /><br> <button id="prevBtn">Prev</button> <button id="nextBtn">Next</button> <script type="text/typescript"> // Images array const images = [ 'https://via.placeholder.com/400x200?text=1', 'https://via.placeholder.com/400x200?text=2', 'https://via.placeholder.com/400x200?text=3', ]; // Elements const sliderImage = document.getElementById('sliderImage') as HTMLImageElement; const prevBtn = document.getElementById('prevBtn') as HTMLButtonElement; const nextBtn = document.getElementById('nextBtn') as HTMLButtonElement; let currentIndex = 0; // Update image src function updateImage() { sliderImage.src = images[currentIndex]; } // Prev button prevBtn.addEventListener('click', () => { currentIndex = (currentIndex - 1 + images.length) % images.length; updateImage(); }); // Next button nextBtn.addEventListener('click', () => { currentIndex = (currentIndex + 1) % images.length; updateImage(); }); </script>
<!-- Show a random quote from list on button click --> <button id="newQuoteBtn">New Quote</button><br> <div id="quoteDisplay"></div> <script type="text/typescript"> // Quotes array const quotes = [ 'The best way to get started is to quit talking and begin doing.', 'Don’t let yesterday take up too much of today.', 'It’s not whether you get knocked down, it’s whether you get up.', ]; // Elements const newQuoteBtn = document.getElementById('newQuoteBtn') as HTMLButtonElement; const quoteDisplay = document.getElementById('quoteDisplay') as HTMLDivElement; // Show random quote newQuoteBtn.addEventListener('click', () => { const index = Math.floor(Math.random() * quotes.length); quoteDisplay.textContent = quotes[index]; }); </script>
<!-- Basic calculator: add, subtract, multiply, divide --> <input type="number" id="num1" placeholder="Number 1" /><br> <input type="number" id="num2" placeholder="Number 2" /><br> <select id="operation"> <option value="add">Add</option> <option value="subtract">Subtract</option> <option value="multiply">Multiply</option> <option value="divide">Divide</option> </select><br> <button id="calculateBtn">Calculate</button><br> <div id="calcResult"></div> <script type="text/typescript"> // Elements const num1Input = document.getElementById('num1') as HTMLInputElement; const num2Input = document.getElementById('num2') as HTMLInputElement; const operationSelect = document.getElementById('operation') as HTMLSelectElement; const calculateBtn = document.getElementById('calculateBtn') as HTMLButtonElement; const calcResult = document.getElementById('calcResult') as HTMLDivElement; // Calculate on button click calculateBtn.addEventListener('click', () => { const n1 = parseFloat(num1Input.value); const n2 = parseFloat(num2Input.value); const op = operationSelect.value; if (isNaN(n1) || isNaN(n2)) { calcResult.textContent = 'Please enter valid numbers.'; return; } let result: number; switch (op) { case 'add': result = n1 + n2; break; case 'subtract': result = n1 - n2; break; case 'multiply': result = n1 * n2; break; case 'divide': if (n2 === 0) { calcResult.textContent = 'Cannot divide by zero.'; return; } result = n1 / n2; break; default: calcResult.textContent = 'Invalid operation.'; return; } calcResult.textContent = `Result: ${result}`; }); </script>