20 JavaScript Coding Exercises Source Code included

Coding Exercises

Source Code included!!!!

1. Change Background Color

Objective: Create a web page with a button that changes the background color of the page when clicked.

<!DOCTYPE html>

<html>

<head>

 <title>Change Background Color</title>

</head>

<body>

 <button id=”changeColorBtn”>Change Background Color</button>

 <script>

 document.getElementById(‘changeColorBtn’).addEventListener(‘click’, function() {

 document.body.style.backgroundColor = ‘lightblue’;

 });

 </script>

</body>

</html>

2. Toggle Image Display

Objective: Implement a feature to toggle the visibility of an image when a button is clicked.

<!DOCTYPE html>

<html>

<head>

 <title>Toggle Image Display</title>

</head>

<body>

 <button id=”toggleImageBtn”>Toggle Image</button>

 <img id=”toggleImage” src=”example.jpg” alt=”Image” style=”display:none;”>

 <script>

 document.getElementById(‘toggleImageBtn’).addEventListener(‘click’, function() {

 var img = document.getElementById(‘toggleImage’);

 img.style.display = img.style.display === ‘none’ ? ‘block’ : ‘none’;

 });

 </script>

</body>

</html>

3. Form Validation

Objective: Create a form that validates an email input field and displays a message if the input is not a valid email address.

<!DOCTYPE html>

<html>

<head>

 <title>Form Validation</title>

</head>

<body>

 <form id=”emailForm”>

 Email: <input type=”email” id=”emailInput”>

 <button type=”submit”>Submit</button>

 <p id=”message”></p>

 </form>

 <script>

 document.getElementById(’emailForm’).addEventListener(‘submit’, function(event) {

 event.preventDefault();

 var email = document.getElementById(’emailInput’).value;

 var message = ”;

 if (!email.includes(‘@’)) {

 message = ‘Please enter a valid email address.’;

 } else {

 message = ‘Email is valid!’;

 }

 document.getElementById(‘message’).innerText = message;

 });

 </script>

</body>

</html>

4. Fetch and Display Data

Objective: Fetch data from a public API and display the results in a list.

<!DOCTYPE html>

<html>

<head>

 <title>Fetch and Display Data</title>

</head>

<body>

 <ul id=”dataList”></ul>

 <script>

 fetch(‘https://jsonplaceholder.typicode.com/posts’)

 .then(response => response.json())

 .then(data => {

 const list = document.getElementById(‘dataList’);

 data.forEach(item => {

 const li = document.createElement(‘li’);

 li.textContent = item.title;

 list.appendChild(li);

 });

 });

 </script>

</body>

</html>

5. Create a To-Do List

Objective: Develop a simple to-do list where users can add items to a list and remove them once completed.

<!DOCTYPE html>

<html>

<head>

 <title>To-Do List</title>

 <style>

 .todo-item { cursor: pointer; }

 </style>

</head>

<body>

 <input type=”text” id=”todoInput”>

 <button id=”addTodoBtn”>Add To-Do</button>

 <ul id=”todoList”></ul>

 <script>

 document.getElementById(‘addTodoBtn’).addEventListener(‘click’, function() {

 var input = document.getElementById(‘todoInput’);

 var itemText = input.value;

 input.value = ”; // Clear input field

 var li = document.createElement(‘li’);

 li.textContent = itemText;

 li.classList.add(‘todo-item’);

 li.addEventListener(‘click’, function() {

 this.parentNode.removeChild(this);

 });

 document.getElementById(‘todoList’).appendChild(li);

 });

 </script>

</body>

</html>

6. Simple Calculator

Objective: Implement a simple calculator that can perform basic arithmetic operations like addition, subtraction, multiplication, and division.

<!DOCTYPE html>

<html>

<head>

 <title>Simple Calculator</title>

</head>

<body>

 <input type=”text” id=”number1″>

 <select id=”operation”>

 <option value=”add”>+</option>

 <option value=”subtract”>-</option>

 <option value=”multiply”>*</option>

 <option value=”divide”>/</option>

 </select>

 <input type=”text” id=”number2″>

 <button id=”calculateBtn”>Calculate</button>

 <p id=”result”></p>

 <script>

 document.getElementById(‘calculateBtn’).addEventListener(‘click’, function() {

 var num1 = parseFloat(document.getElementById(‘number1’).value);

 var num2 = parseFloat(document.getElementById(‘number2’).value);

 var operation = document.getElementById(‘operation’).value;

 var result;

 switch(operation) {

 case ‘add’:

 result = num1 + num2;

 break;

 case ‘subtract’:

 result = num1 – num2;

 break;

 case ‘multiply’:

 result = num1 * num2;

 break;

 case ‘divide’:

 result = num1 / num2;

 break;

 }

 document.getElementById(‘result’).innerText = ‘Result: ‘ + result;

 });

 </script>

</body>

</html>

7. Countdown Timer

Objective: Create a countdown timer that counts down from a specified time and displays a message when the countdown reaches zero.

<!DOCTYPE html>

<html>

<head>

 <title>Countdown Timer</title>

</head>

<body>

 <div id=”timer”></div>

 <script>

 var countdownDuration = 10; // 10 seconds for example

 var timerDisplay = document.getElementById(‘timer’);

 var countdown = setInterval(function() {

 timerDisplay.innerText = countdownDuration + ‘ seconds remaining’;

 countdownDuration–;

 if (countdownDuration < 0) {

 clearInterval(countdown);

 timerDisplay.innerText = ‘Time is up!’;

 }

 }, 1000);

 </script>

</body>

</html>

8. Interactive Quiz

Objective: Design an interactive quiz with multiple-choice questions. After submitting, show the correct answers and the user’s score.

<!DOCTYPE html>

<html>

<head>

 <title>Interactive Quiz</title>

</head>

<body>

 <div id=”quiz”></div>

 <button id=”submitQuizBtn”>Submit Answers</button>

 <div id=”result”></div>

 <script>

 const questions = [

 { question: ‘What is 2 + 2?’, choices: [‘2’, ‘3’, ‘4’, ‘5’], correctAnswer: ‘4’ },

 { question: ‘What is the capital of France?’, choices: [‘Paris’, ‘London’, ‘Berlin’, ‘Madrid’], correctAnswer: ‘Paris’ }

 ];

 function displayQuestions() {

 const quizContainer = document.getElementById(‘quiz’);

 questions.forEach((q, index) => {

 const questionDiv = document.createElement(‘div’);

 questionDiv.innerHTML = `<p>${q.question}</p>`;

 q.choices.forEach(choice => {

 questionDiv.innerHTML += `<input type=”radio” name=”question${index}” value=”${choice}”>${choice}<br>`;

 });

 quizContainer.appendChild(questionDiv);

 });

 }

 document.getElementById(‘submitQuizBtn’).addEventListener(‘click’, function() {

 let score = 0;

 questions.forEach((q, index) => {

 const selectedAnswer = document.querySelector(`input[name=”question${index}”]:checked`)?.value;

 if (selectedAnswer === q.correctAnswer) {

 score++;

 }

 });

 document.getElementById(‘result’).innerHTML = `You scored ${score} out of ${questions.length}`;

 });

 displayQuestions();

 </script>

</body>

</html>

9. Dynamic Content Loading

Objective: Dynamically load content into a page section without reloading the page when a button is clicked.

<!DOCTYPE html>

<html>

<head>

 <title>Dynamic Content Loading</title>

</head>

<body>

 <button id=”loadContentBtn”>Load Content</button>

 <div id=”content”></div>

 <script>

 document.getElementById(‘loadContentBtn’).addEventListener(‘click’, function() {

 document.getElementById(‘content’).innerHTML = ‘<p>New content loaded!</p>’;

 });

 </script>

</body>

</html>

10. Image Slider

Objective: Create an image slider that cycles through a series of images when the next and previous buttons are clicked.

<!DOCTYPE html>

<html>

<head>

 <title>Image Slider</title>

 <style>

 .slider { width: 500px; overflow: hidden; }

 .slider img { width: 500px; display: none; }

 </style>

</head>

<body>

 <div class=”slider”>

 <img src=”image1.jpg” alt=”Image 1″ style=”display:block;”>

 <img src=”image2.jpg” alt=”Image 2″>

 <img src=”image3.jpg” alt=”Image 3″>

 </div>

 <button id=”prevBtn”>Previous</button>

 <button id=”nextBtn”>Next</button>

 <script>

 var images = document.querySelectorAll(‘.slider img’);

 var currentImageIndex = 0;

 function showImage(index) {

 images.forEach((img, i) => {

 img.style.display = i === index ? ‘block’ : ‘none’;

 });

 }

 document.getElementById(‘nextBtn’).addEventListener(‘click’, function() {

 currentImageIndex = (currentImageIndex + 1) % images.length;

 showImage(currentImageIndex);

 });

 document.getElementById(‘prevBtn’).addEventListener(‘click’, function() {

 currentImageIndex = (currentImageIndex – 1 + images.length) % images.length;

 showImage(currentImageIndex);

 });

 showImage(currentImageIndex);

 </script>

</body>

</html>

11. Modal Popup

Objective: Create a modal popup that appears when a button is clicked and can be closed with a close button.

<!DOCTYPE html>

<html>

<head>

 <title>Modal Popup</title>

 <style>

 .modal { display: none; position: fixed; z-index: 1; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.4); }

 .modal-content { background-color: #fefefe; margin: 15% auto; padding: 20px; border: 1px solid #888; width: 80%; }

 </style>

</head>

<body>

 <button id=”openModalBtn”>Open Modal</button>

 <div id=”myModal” class=”modal”>

 <div class=”modal-content”>

 <span id=”closeModalBtn”>&times;</span>

 <p>Some text in the Modal..</p>

 </div>

 </div>

 <script>

 var modal = document.getElementById(‘myModal’);

 var btn = document.getElementById(‘openModalBtn’);

 var span = document.getElementById(‘closeModalBtn’);

 btn.onclick = function() {

 modal.style.display = “block”;

 }

 span.onclick = function() {

 modal.style.display = “none”;

 }

 window.onclick = function(event) {

 if (event.target == modal) {

 modal.style.display = “none”;

 }

 }

 </script>

</body>

</html>

12. Dynamic Select Options

Objective: Dynamically populate a select dropdown with options from an array.

<!DOCTYPE html>

<html>

<head>

 <title>Dynamic Select Options</title>

</head>

<body>

 <select id=”dynamicSelect”></select>

 <script>

 const options = [‘Option 1’, ‘Option 2’, ‘Option 3’];

 const select = document.getElementById(‘dynamicSelect’);

 options.forEach(option => {

 const opt = document.createElement(‘option’);

 opt.value = option;

 opt.innerHTML = option;

 select.appendChild(opt);

 });

 </script>

</body>

</html>

13. Accordion

Objective: Implement an accordion where clicking on a section header expands or collapses the section content.

<!DOCTYPE html>

<html>

<head>

 <title>Accordion</title>

 <style>

 .accordion { background-color: #eee; color: #444; cursor: pointer; padding: 18px; width: 100%; border: none; text-align: left; outline: none; font-size: 15px; transition: 0.4s; }

 .active, .accordion:hover { background-color: #ccc; }

 .panel { padding: 0 18px; display: none; background-color: white; overflow: hidden; }

 </style>

</head>

<body>

 <button class=”accordion”>Section 1</button>

 <div class=”panel”>

 <p>Section 1 content…</p>

 </div>

 <button class=”accordion”>Section 2</button>

 <div class=”panel”>

 <p>Section 2 content…</p>

 </div>

 <script>

 var acc = document.getElementsByClassName(“accordion”);

 for (var i = 0; i < acc.length; i++) {

 acc[i].addEventListener(“click”, function() {

 this.classList.toggle(“active”);

 var panel = this.nextElementSibling;

 if (panel.style.display === “block”) {

 panel.style.display = “none”;

 } else {

 panel.style.display = “block”;

 }

 });

 }

 </script>

</body>

</html>

14. Filter List

Objective: Implement a search feature that filters through a list of items and shows only those matching the query.

<!DOCTYPE html>

<html>

<head>

 <title>Filter List</title>

</head>

<body>

 <input type=”text” id=”filterInput” placeholder=”Search for names..”>

 <ul id=”namesList”>

 <li>John</li>

 <li>Jane</li>

 <li>Mike</li>

 <li>Mary</li>

 </ul>

 <script>

 document.getElementById(‘filterInput’).addEventListener(‘keyup’, function() {

 var input = document.getElementById(‘filterInput’).value.toUpperCase();

 var ul = document.getElementById(“namesList”);

 var li = ul.getElementsByTagName(‘li’);

 for (var i = 0; i < li.length; i++) {

 var txtValue = li[i].textContent || li[i].innerText;

 if (txtValue.toUpperCase().indexOf(input) > -1) {

 li[i].style.display = “”;

 } else {

 li[i].style.display = “none”;

 }

 }

 });

 </script>

</body>

</html>

15. Sort Table

Objective: Create a table that can be sorted by column when the header is clicked.

<!DOCTYPE html>

<html>

<head>

 <title>Sort Table</title>

</head>

<body>

 <table id=”sortTable”>

 <thead>

 <tr>

 <th onclick=”sortTable(0)”>Name</th>

 <th onclick=”sortTable(1)”>Age</th>

 </tr>

 </thead>

 <tbody>

 <tr>

 <td>John</td>

 <td>25</td>

 </tr>

 <tr>

 <td>Jane</td>

 <td>20</td>

 </tr>

 <tr>

 <td>Mike</td>

 <td>30</td>

 </tr>

 </tbody>

 </table>

 <script>

 function sortTable(n) {

 var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;

 table = document.getElementById(“sortTable”);

 switching = true;

 // Set the sorting direction to ascending:

 dir = “asc”; 

 while (switching) {

 switching = false;

 rows = table.rows;

 for (i = 1; i < (rows.length – 1); i++) {

 shouldSwitch = false;

 x = rows[i].getElementsByTagName(“TD”)[n];

 y = rows[i + 1].getElementsByTagName(“TD”)[n];

 if (dir == “asc”) {

 if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {

 shouldSwitch= true;

 break;

 }

 } else if (dir == “desc”) {

 if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {

 shouldSwitch = true;

 break;

 }

 }

 }

 if (shouldSwitch) {

 rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);

 switching = true;

 switchcount ++; 

 } else {

 if (switchcount == 0 && dir == “asc”) {

 dir = “desc”;

 switching = true;

 }

 }

 }

 }

 </script>

</body>

</html>

16. Sticky Navigation Bar

Objective: Create a navigation bar that becomes fixed to the top of the viewport when you scroll past it.

<!DOCTYPE html>

<html>

<head>

 <title>Sticky Navigation Bar</title>

 <style>

 .navbar { overflow: hidden; background-color: #333; }

 .navbar a { float: left; display: block; color: white; text-align: center; padding: 14px 20px; text-decoration: none; }

 .sticky { position: fixed; top: 0; width: 100%; }

 </style>

</head>

<body>

 <div class=”navbar” id=”navbar”>

 <a href=”#home”>Home</a>

 <a href=”#news”>News</a>

 <a href=”#contact”>Contact</a>

 </div>

 <script>

 window.onscroll = function() {myFunction()};

 var navbar = document.getElementById(“navbar”);

 var sticky = navbar.offsetTop;

 function myFunction() {

 if (window.pageYOffset >= sticky) {

 navbar.classList.add(“sticky”)

 } else {

 navbar.classList.remove(“sticky”);

 }

 }

 </script>

</body>

</html>

17. Slideshow

Objective: Develop a slideshow that automatically transitions between images every few seconds.

<!DOCTYPE html>

<html>

<head>

 <title>Slideshow</title>

 <style>

 .slideshow-container { max-width: 1000px; position: relative; margin: auto; }

 .mySlides { display: none; }

 .fade { animation-name: fade; animation-duration: 1.5s; }

 @keyframes fade { from {opacity: .4} to {opacity: 1} }

 </style>

</head>

<body>

 <div class=”slideshow-container”>

 <div class=”mySlides fade”>

 <img src=”img1.jpg” style=”width:100%”>

 </div>

 <div class=”mySlides fade”>

 <img src=”img2.jpg” style=”width:100%”>

 </div>

 <div class=”mySlides fade”>

 <img src=”img3.jpg” style=”width:100%”>

 </div>

 </div>

 <script>

 var slideIndex = 0;

 showSlides();

 function showSlides() {

 var i;

 var slides = document.getElementsByClassName(“mySlides”);

 for (i = 0; i < slides.length; i++) {

 slides[i].style.display = “none”; 

 }

 slideIndex++;

 if (slideIndex > slides.length) {slideIndex = 1} 

 slides[slideIndex-1].style.display = “block”; 

 setTimeout(showSlides, 2000); // Change image every 2 seconds

 }

 </script>

</body>

</html>

18. Expand/Collapse Content

Objective: Create a section of content that can be expanded or collapsed with a button click.

<!DOCTYPE html>

<html>

<head>

 <title>Expand/Collapse Content</title>

</head>

<body>

 <button onclick=”toggleContent()”>Show More/Less</button>

 <div id=”expandableContent” style=”display:none;”>

 <p>Here is some more content you can see after you click the button!</p>

 </div>

 <script>

 function toggleContent() {

 var content = document.getElementById(“expandableContent”);

 if (content.style.display === “none”) {

 content.style.display = “block”;

 } else {

 content.style.display = “none”;

 }

 }

 </script>

</body>

</html>

19. Digital Clock

Objective: Display a live digital clock on the web page that updates every second.

<!DOCTYPE html>

<html>

<head>

 <title>Digital Clock</title>

</head>

<body>

 <div id=”digitalClock”></div>

 <script>

 function showTime() {

 var date = new Date();

 var h = date.getHours(); // 0 – 23

 var m = date.getMinutes(); // 0 – 59

 var s = date.getSeconds(); // 0 – 59

 var session = h >= 12 ? ‘PM’ : ‘AM’;

 h = h % 12;

 h = h ? h : 12; // the hour ‘0’ should be ’12’

 m = m < 10 ? ‘0’ + m : m;

 s = s < 10 ? ‘0’ + s : s;

 var time = h + “:” + m + “:” + s + ” ” + session;

 document.getElementById(“digitalClock”).innerText = time;

 document.getElementById(“digitalClock”).textContent = time;

 setTimeout(showTime, 1000);

 }

 showTime();

 </script>

</body>

</html>

20. Typing Speed Tester

Objective: Create a simple typing speed tester that measures how quickly the user can type a provided sample text.

<!DOCTYPE html>

<html>

<head>

 <title>Typing Speed Tester</title>

</head>

<body>

 <p id=”sampleText”>Type this text as fast as you can!</p>

 <textarea id=”typingArea” rows=”10″ cols=”50″></textarea>

 <button id=”startBtn”>Start</button>

 <p id=”result”></p>

 <script>

 document.getElementById(‘startBtn’).addEventListener(‘click’, function() {

 var startTime = new Date().getTime();

 var sampleText = document.getElementById(‘sampleText’).innerText;

 var typingArea = document.getElementById(‘typingArea’);

 typingArea.value = ”;

 typingArea.focus();

 typingArea.oninput = function() {

 if(typingArea.value === sampleText) {

 var endTime = new Date().getTime();

 var elapsedTime = (endTime – startTime) / 1000; // in seconds

 document.getElementById(‘result’).innerText = ‘Your time: ‘ + elapsedTime + ‘ seconds’;

 typingArea.oninput = null; // stop the test

 }

 };

 });

 </script>

</body>

</html>

These exercises are designed to progressively build a learner’s JavaScript, HTML, and CSS skills through practical, hands-on coding tasks. They can be used as part of a course curriculum, self-study, or coding practice to reinforce web development concepts.