Free First 2 chapters FrontEnd Code PlayGround HTML CSS and JavaScript Exercises to Develop Your Skills

🚀 Free on Kindle Until June 8th, 2024! 🚀

Get source code for this book at https://github.com/lsvekis/FrontEnd-Code-PlayGround

Amazon US https://www.amazon.com/dp/B0D2G6BG3J

CAN https://www.amazon.ca/dp/B0D2G6BG3J

“FrontEnd Code Playground: HTML, CSS, and JavaScript Exercises to Develop Your Skills” is a comprehensive guide designed to accelerate your learning journey in front-end development. Authored by Laurence Lars Svekis, a seasoned web developer and educator, this book is tailored to offer an engaging and practical approach to mastering HTML, CSS, and JavaScript, with a particular focus on DOM manipulation.

This book stands out with its unique style, crafted to make learning both swift and enjoyable. The exercises are designed not just to teach you the basics but to immerse you in real-world scenarios where you can apply what you’ve learned. Each exercise comes with multiple-choice quiz questions to reinforce your understanding and ensure you grasp the key concepts thoroughly.

The chapters are structured to progressively build your skills, starting with fundamental HTML and CSS, and moving into more complex JavaScript functionalities. You’ll work on a variety of projects, such as creating a dynamic image gallery, building an interactive quiz, and developing a unit converter. These projects are not only practical but also fun, keeping you motivated and eager to learn more.

One of the unique aspects of this book is its emphasis on quick learning through practice. The exercises are designed to be concise yet comprehensive, allowing you to see immediate results from your coding efforts. This method helps to build confidence and competence, ensuring you can quickly transition from theory to practice.

In addition to the exercises, the book offers quiz questions at the end of each chapter to test your knowledge and reinforce what you’ve learned. These questions are crafted to challenge your understanding and ensure you’re ready to tackle real-world web development problems.

Laurence’s teaching style is clear and accessible, making complex concepts easy to understand. His extensive experience in online education shines through in the way he explains the material, making it suitable for learners at all levels. Whether you’re a complete beginner or someone looking to polish their skills, this book has something for you.

The book also delves into the “weird parts” of JavaScript, preparing you to handle quirks and complexities you might encounter in real-world coding. By working through these exercises, you’ll develop a solid foundation and a deep understanding of front-end development, preparing you to create interactive, dynamic web applications.

Furthermore, “FrontEnd Code Playground” is a tribute to the collaborative spirit of the coding community. Laurence’s interactions with students and his contributions to educational content reflect a deep commitment to sharing knowledge and fostering learning. This book is a testament to that dedication, providing a resource that helps you not only learn but excel in the world of web development.

Join the journey with “FrontEnd Code Playground” and transform your coding skills with hands-on exercises and insightful quiz questions that make learning fast, effective, and enjoyable. This book is your gateway to mastering front-end development and becoming a proficient web developer. Dive in, practice hard, and watch your skills grow!

Change Background Color

Description:

In this exercise, students will create a simple webpage with a button that changes the background color of the page when clicked. This exercise introduces basic DOM manipulation and event handling.

Topics Covered:

  • HTML structure
  • CSS styling
  • JavaScript event listeners
  • DOM manipulation

HTML:

<!DOCTYPE html>

<html lang=”en”>

<head>

    <meta charset=”UTF-8″>

    <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>

    <title>Change Background Color</title>

    <link rel=”stylesheet” href=”styles.css”>

</head>

<body>

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

    <script src=”script.js”></script>

</body>

</html>

CSS:

body {

    font-family: Arial, sans-serif;

    display: flex;

    justify-content: center;

    align-items: center;

    height: 100vh;

    margin: 0;

    background-color: #f0f0f0;

}

button {

    padding: 10px 20px;

    font-size: 16px;

    cursor: pointer;

}

JavaScript:

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

    document.body.style.backgroundColor = getRandomColor();

});

function getRandomColor() {

    const letters = ‘0123456789ABCDEF’;

    let color = ‘#’;

    for (let i = 0; i < 6; i++) {

        color += letters[Math.floor(Math.random() * 16)];

    }

    return color;

}

Show/Hide Text

Description:

In this exercise, students will create a webpage with a button that toggles the visibility of a paragraph of text. This exercise introduces the concepts of showing and hiding elements using JavaScript.

Topics Covered:

  • HTML structure
  • CSS styling
  • JavaScript event listeners
  • DOM manipulation (show/hide elements)

HTML:

<!DOCTYPE html>

<html lang=”en”>

<head>

    <meta charset=”UTF-8″>

    <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>

    <title>Show/Hide Text</title>

    <link rel=”stylesheet” href=”styles.css”>

</head>

<body>

    <button id=”toggleTextButton”>Show/Hide Text</button>

    <p id=”text” style=”display: none;”>This is a sample text that can be shown or hidden.</p>

    <script src=”script.js”></script>

</body>

</html>

CSS:

body {

    font-family: Arial, sans-serif;

    display: flex;

    flex-direction: column;

    align-items: center;

    height: 100vh;

    justify-content: center;

    margin: 0;

}

button {

    padding: 10px 20px;

    font-size: 16px;

    cursor: pointer;

    margin-bottom: 20px;

}

p {

    font-size: 18px;

}

JavaScript:

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

    const text = document.getElementById(‘text’);

    if (text.style.display === ‘none’) {

        text.style.display = ‘block’;

    } else {

        text.style.display = ‘none’;

    }

});

Add Items to a List

Description:

In this exercise, students will create a webpage with an input field and a button to add items to a list. This exercise introduces creating new elements and appending them to the DOM.

Topics Covered:

  • HTML structure
  • CSS styling
  • JavaScript event listeners
  • DOM manipulation (creating and appending elements)

HTML:

<!DOCTYPE html>

<html lang=”en”>

<head>

    <meta charset=”UTF-8″>

    <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>

    <title>Add Items to List</title>

    <link rel=”stylesheet” href=”styles.css”>

</head>

<body>

    <input type=”text” id=”itemInput” placeholder=”Enter item”>

    <button id=”addItemButton”>Add Item</button>

    <ul id=”itemList”></ul>

    <script src=”script.js”></script>

</body>

</html>

CSS:

body {

    font-family: Arial, sans-serif;

    display: flex;

    flex-direction: column;

    align-items: center;

    height: 100vh;

    justify-content: center;

    margin: 0;

}

input {

    padding: 10px;

    font-size: 16px;

    margin-bottom: 10px;

}

button {

    padding: 10px 20px;

    font-size: 16px;

    cursor: pointer;

    margin-bottom: 20px;

}

ul {

    list-style-type: none;

    padding: 0;

}

li {

    font-size: 18px;

    margin: 5px 0;

}

JavaScript:

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

    const itemInput = document.getElementById(‘itemInput’);

    const newItemText = itemInput.value;

    if (newItemText !== ”) {

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

        newItem.textContent = newItemText;

        document.getElementById(‘itemList’).appendChild(newItem);

        itemInput.value = ”;

    }

});

Multiple Choice Questions

What event listener is used to detect a button click in JavaScript?

a) click

b) mouseover

c) keydown

d) load

Answer: a) click Explanation: The click event listener is used to detect when a button is clicked.

How can you change the background color of a webpage using JavaScript?

a) document.body.color

b) document.body.backgroundColor

c) document.body.style.backgroundColor

d) document.body.style.color

Answer: c) document.body.style.backgroundColor Explanation: To change the background color, you need to use document.body.style.backgroundColor.

Which CSS property is used to hide an element in the DOM?

a) visibility

b) opacity

c) display

d) hidden

Answer: c) display Explanation: The display property can be set to none to hide an element.

How do you create a new HTML element using JavaScript?

a) document.createElement()

b) document.newElement()

c) document.create()

d) document.new()

Answer: a) document.createElement() Explanation: The document.createElement() method is used to create a new HTML element.

In the exercise “Add Items to a List,” what function appends the new item to the list?

a) append()

b) addChild()

c) appendChild()

d) add()

Answer: c) appendChild() Explanation: The appendChild() method is used to add a new child element to a parent node.

What is the purpose of the getRandomColor function in the Change Background Color exercise?

A) To change the text color

B) To generate a random background color

C) To change the font size

D) To generate a random font style

Answer: B

Explanation: The getRandomColor function generates a random color code that is used to change the background color of the page.

What event listener is used to trigger the color change in the Change Background Color exercise?

A) mouseover

B) keydown

C) click

D) scroll

Answer: C

Explanation: The click event listener is used to trigger the background color change when the button is clicked.

Which HTML element has the ID changeColorButton in the Change Background Color exercise?

A) <body>

B) <button>

C) <div>

D) <span>

Answer: B

Explanation: The <button> element has the ID changeColorButton.

What does the Math.floor(Math.random() * 16) expression do in the getRandomColor function?

A) It generates a random number between 0 and 16.

B) It generates a random number between 0 and 15.

C) It generates a random number between 1 and 16.

D) It generates a random number between 1 and 15.

Answer: B

Explanation: Math.random() generates a random number between 0 and 1. Multiplying by 16 and using Math.floor rounds it down to a whole number between 0 and 15.

What initial CSS display property value is set for the paragraph in the Show/Hide Text exercise?

A) block

B) inline

C) flex

D) none

Answer: D

Explanation: The initial CSS display property value for the paragraph is set to none, making it hidden.

What condition is checked to toggle the text visibility in the Show/Hide Text exercise?

A) If the text content is empty

B) If the text display is none

C) If the button is clicked

D) If the text display is block

Answer: B

Explanation: The condition checks if the text’s display property is none to toggle its visibility.

What happens when the toggleTextButton is clicked and the text is already visible in the Show/Hide Text exercise?

A) The text becomes italic

B) The text is hidden

C) The text color changes

D) The text font size increases

Answer: B

Explanation: If the text is already visible, clicking the button hides the text by setting its display property to none.

What happens when the addItemButton is clicked in the Add Items to a List exercise?

A) A new paragraph is added

B) A new list item is added

C) The input field is cleared

D) Both B and C

Answer: D

Explanation: When the button is clicked, a new list item is added, and the input field is cleared.

Which HTML element is used to capture the user’s input in the Add Items to a List exercise?

A) <input>

B) <textarea>

C) <div>

D) <span>

Answer: A

Explanation: The <input> element captures the user’s input.

What method is used to create a new list item element in the Add Items to a List exercise?

A) document.createElement(‘li’)

B) document.createElement(‘div’)

C) document.createElement(‘p’)

D) document.createElement(‘span’)

Answer: A

Explanation: The document.createElement(‘li’) method is used to create a new list item element.

Display Current Date and Time

Description:

In this exercise, students will create a webpage with a button that displays the current date and time when clicked. This exercise introduces working with JavaScript dates and displaying text on a webpage.

Topics Covered:

  • HTML structure
  • CSS styling
  • JavaScript event listeners
  • Working with JavaScript Date objects
  • DOM manipulation

HTML:

<!DOCTYPE html>

<html lang=”en”>

<head>

    <meta charset=”UTF-8″>

    <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>

    <title>Display Date and Time</title>

    <link rel=”stylesheet” href=”styles.css”>

</head>

<body>

    <button id=”showDateTimeButton”>Show Date and Time</button>

    <p id=”dateTimeDisplay”></p>

    <script src=”script.js”></script>

</body>

</html>

CSS:

body {

    font-family: Arial, sans-serif;

    display: flex;

    flex-direction: column;

    align-items: center;

    height: 100vh;

    justify-content: center;

    margin: 0;

}

button {

    padding: 10px 20px;

    font-size: 16px;

    cursor: pointer;

    margin-bottom: 20px;

}

p {

    font-size: 18px;

}

JavaScript:

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

    const now = new Date();

    const dateTimeString = now.toLocaleString();

    document.getElementById(‘dateTimeDisplay’).textContent = dateTimeString;

});

Change Text Content

Description:

In this exercise, students will create a webpage with an input field and a button. When the button is clicked, the text content of a paragraph is updated with the text entered in the input field. This exercise introduces updating text content dynamically using JavaScript.

Topics Covered:

  • HTML structure
  • CSS styling
  • JavaScript event listeners
  • DOM manipulation (updating text content)

HTML:

<!DOCTYPE html>

<html lang=”en”>

<head>

    <meta charset=”UTF-8″>

    <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>

    <title>Change Text Content</title>

    <link rel=”stylesheet” href=”styles.css”>

</head>

<body>

    <input type=”text” id=”textInput” placeholder=”Enter new text”>

    <button id=”changeTextButton”>Change Text</button>

    <p id=”textDisplay”>This is the original text.</p>

    <script src=”script.js”></script>

</body>

</html>

CSS:

body {

    font-family: Arial, sans-serif;

    display: flex;

    flex-direction: column;

    align-items: center;

    height: 100vh;

    justify-content: center;

    margin: 0;

}

input {

    padding: 10px;

    font-size: 16px;

    margin-bottom: 10px;

}

button {

    padding: 10px 20px;

    font-size: 16px;

    cursor: pointer;

    margin-bottom: 20px;

}

p {

    font-size: 18px;

}

JavaScript:

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

    const newText = document.getElementById(‘textInput’).value;

    document.getElementById(‘textDisplay’).textContent = newText;

});

Highlight List Items

Description:

In this exercise, students will create a webpage with a list of items. When an item is clicked, its background color changes to highlight it. This exercise introduces event delegation and dynamically updating styles.

Topics Covered:

  • HTML structure
  • CSS styling
  • JavaScript event listeners
  • Event delegation
  • DOM manipulation (updating styles)

HTML:

<!DOCTYPE html>

<html lang=”en”>

<head>

    <meta charset=”UTF-8″>

    <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>

    <title>Highlight List Items</title>

    <link rel=”stylesheet” href=”styles.css”>

</head>

<body>

    <ul id=”itemList”>

        <li>Item 1</li>

        <li>Item 2</li>

        <li>Item 3</li>

        <li>Item 4</li>

    </ul>

    <script src=”script.js”></script>

</body>

</html>

CSS:

body {

    font-family: Arial, sans-serif;

    display: flex;

    flex-direction: column;

    align-items: center;

    height: 100vh;

    justify-content: center;

    margin: 0;

}

ul {

    list-style-type: none;

    padding: 0;

}

li {

    font-size: 18px;

    margin: 5px 0;

    padding: 10px;

    cursor: pointer;

}

li.highlight {

    background-color: yellow;

}

JavaScript:

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

    if (event.target.tagName === ‘LI’) {

        const items = document.querySelectorAll(‘li’);

        items.forEach(item => item.classList.remove(‘highlight’));

        event.target.classList.add(‘highlight’);

    }

});

Dynamic Image Gallery

Description:

In this exercise, students will create a simple image gallery. When a thumbnail is clicked, a larger version of the image will be displayed. This exercise introduces handling click events and dynamically updating image sources.

Topics Covered:

  • HTML structure
  • CSS styling
  • JavaScript event listeners
  • DOM manipulation (changing image sources)

HTML:

<!DOCTYPE html>

<html lang=”en”>

<head>

    <meta charset=”UTF-8″>

    <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>

    <title>Dynamic Image Gallery</title>

    <link rel=”stylesheet” href=”styles.css”>

</head>

<body>

    <div id=”gallery”>

        <img src=”thumbnail1.jpg” alt=”Thumbnail 1″ class=”thumbnail”>

        <img src=”thumbnail2.jpg” alt=”Thumbnail 2″ class=”thumbnail”>

        <img src=”thumbnail3.jpg” alt=”Thumbnail 3″ class=”thumbnail”>

    </div>

    <div id=”display”>

        <img id=”largeImage” src=”placeholder.jpg” alt=”Large Image”>

    </div>

    <script src=”script.js”></script>

</body>

</html>

CSS:

body {

    font-family: Arial, sans-serif;

    display: flex;

    flex-direction: column;

    align-items: center;

    height: 100vh;

    justify-content: center;

    margin: 0;

}

#gallery {

    display: flex;

    gap: 10px;

}

.thumbnail {

    width: 100px;

    cursor: pointer;

}

#display {

    margin-top: 20px;

}

#largeImage {

    width: 300px;

}

JavaScript:

document.querySelectorAll(‘.thumbnail’).forEach(thumbnail => {

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

        const largeImage = document.getElementById(‘largeImage’);

        largeImage.src = this.src.replace(‘thumbnail’, ‘large’);

    });

});

Interactive Counter

Description:

In this exercise, students will create an interactive counter with buttons to increment and decrement the count. This exercise introduces updating the DOM based on user input.

Topics Covered:

  • HTML structure
  • CSS styling
  • JavaScript event listeners
  • DOM manipulation (updating text content)

HTML:

<!DOCTYPE html>

<html lang=”en”>

<head>

    <meta charset=”UTF-8″>

    <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>

    <title>Interactive Counter</title>

    <link rel=”stylesheet” href=”styles.css”>

</head>

<body>

    <div id=”counter”>

        <button id=”decrementButton”>-</button>

        <span id=”count”>0</span>

        <button id=”incrementButton”>+</button>

    </div>

    <script src=”script.js”></script>

</body>

</html>

CSS:

body {

    font-family: Arial, sans-serif;

    display: flex;

    flex-direction: column;

    align-items: center;

    height: 100vh;

    justify-content: center;

    margin: 0;

}

#counter {

    display: flex;

    align-items: center;

    gap: 10px;

}

button {

    padding: 10px 20px;

    font-size: 16px;

    cursor: pointer;

}

span {

    font-size: 24px;

    width: 50px;

    text-align: center;

}

JavaScript:

let count = 0;

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

    count++;

    document.getElementById(‘count’).textContent = count;

});

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

    count–;

    document.getElementById(‘count’).textContent = count;

});

Form Validation

Description:

In this exercise, students will create a simple form with validation. When the submit button is clicked, the script will check if all fields are filled and display an alert message if any fields are empty. This exercise introduces basic form validation.

Topics Covered:

  • HTML structure
  • CSS styling
  • JavaScript event listeners
  • Form validation
  • DOM manipulation (alert messages)

HTML:

<!DOCTYPE html>

<html lang=”en”>

<head>

    <meta charset=”UTF-8″>

    <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>

    <title>Form Validation</title>

    <link rel=”stylesheet” href=”styles.css”>

</head>

<body>

    <form id=”myForm”>

        <input type=”text” id=”name” placeholder=”Name”>

        <input type=”email” id=”email” placeholder=”Email”>

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

    </form>

    <script src=”script.js”></script>

</body>

</html>

CSS:

body {

    font-family: Arial, sans-serif;

    display: flex;

    flex-direction: column;

    align-items: center;

    height: 100vh;

    justify-content: center;

    margin: 0;

}

form {

    display: flex;

    flex-direction: column;

    gap: 10px;

}

input {

    padding: 10px;

    font-size: 16px;

    width: 200px;

}

button {

    padding: 10px 20px;

    font-size: 16px;

    cursor: pointer;

}

JavaScript:

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

    const name = document.getElementById(‘name’).value;

    const email = document.getElementById(’email’).value;

    if (name === ” || email === ”) {

        event.preventDefault();

        alert(‘Please fill out all fields.’);

    }

});

Multiple Choice Questions

In the Dynamic Image Gallery exercise, what method is used to add a click event listener to each thumbnail?

a) addEventListener

b) attachEvent

c) onClick

d) addListener

Answer: a) addEventListener Explanation: The addEventListener method is used to attach an event handler to the specified element.

How can you change the source of an image element in JavaScript?

a) element.src

b) element.href

c) element.link

d) element.url

Answer: a) element.src Explanation: The src property of the image element is used to get or set the URL of the image to be displayed.

In the Interactive Counter exercise, what method is used to update the text content of the span element?

a) innerHTML

b) textContent

c) innerText

d) value

Answer: b) textContent Explanation: The textContent property is used to set or return the text content of an element.

Which event is used to detect when a form is submitted in JavaScript?

a) click

b) submit

c) change

d) input

Answer: b) submit Explanation: The submit event is fired when a form is submitted.

In the Form Validation exercise, how can you prevent the form from being submitted if validation fails?

a) return false

b) event.stop

c) event.preventDefault

d) event.prevent

Answer: c) event.preventDefault Explanation: The event.preventDefault method is used to prevent the default action of the event from being triggered.

Dynamic Image Gallery

What is the primary purpose of the forEach method in the Dynamic Image Gallery exercise?

A) To select the first element with a specific class

B) To apply an event listener to each thumbnail

C) To change the image source for all thumbnails

D) To remove all thumbnail images

Answer: B

Explanation: The forEach method is used to apply an event listener to each thumbnail image.

Which event triggers the display of the larger image in the Dynamic Image Gallery exercise?

A) Mouseover

B) Double click

C) Click

D) Key press

Answer: C

Explanation: The click event triggers the display of the larger image when a thumbnail is clicked.

How is the source of the large image updated in the Dynamic Image Gallery exercise?

A) By changing the alt attribute

B) By changing the src attribute

C) By adding a new image element

D) By removing the old image element

Answer: B

Explanation: The src attribute of the large image element is updated to the source of the clicked thumbnail, with the filename modified to point to the larger version.

What class do the thumbnail images have in the Dynamic Image Gallery exercise?

A) gallery

B) display

C) largeImage

D) thumbnail

Answer: D

Explanation: The thumbnail images have the class thumbnail.

Interactive Counter

What happens when the increment button is clicked in the Interactive Counter exercise?

A) The count value is decremented by 1

B) The count value is incremented by 1

C) The count value is reset to 0

D) The count value is displayed as a negative number

Answer: B

Explanation: Clicking the increment button increases the count value by 1.

Where is the current count value displayed in the Interactive Counter exercise?

A) In a <div> element

B) In a <span> element

C) In a <p> element

D) In an <h1> element

Answer: B

Explanation: The current count value is displayed in a <span> element with the ID count.

What JavaScript method is used to update the text content of the count display in the Interactive Counter exercise?

A) innerHTML

B) value

C) textContent

D) appendChild

Answer: C

Explanation: The textContent property is used to update the text content of the count display.

Form Validation

What event is used to validate the form in the Form Validation exercise?

A) Click event on the submit button

B) Keyup event on the input fields

C) Submit event on the form

D) Change event on the form

Answer: C

Explanation: The submit event on the form is used to validate the form when the submit button is clicked.

What method prevents the form from submitting if validation fails in the Form Validation exercise?

A) stopPropagation()

B) preventDefault()

C) stopImmediatePropagation()

D) return false

Answer: B

Explanation: The preventDefault() method prevents the form from submitting if the validation fails.

What message is displayed if any form fields are empty in the Form Validation exercise?

A) “Form submitted successfully”

B) “Please fill out all fields.”

C) “Invalid input”

D) “Submission failed”

Answer: B

Explanation: An alert message saying “Please fill out all fields.” is displayed if any form fields are empty.

What JavaScript object is used to work with dates and times?

a) Time

b) Date

c) Calendar

d) Clock

Answer: b) Date Explanation: The Date object is used to work with dates and times in JavaScript.

How can you update the text content of an HTML element using JavaScript?

a) element.innerText

b) element.textContent

c) element.innerHTML

d) element.updateText

Answer: b) element.textContent Explanation: The textContent property is used to set or return the text content of an element.

What is event delegation?

a) A technique to attach a single event listener to multiple elements

b) A method to prevent event propagation

c) A way to remove an event listener

d) A property to change the event type

Answer: a) A technique to attach a single event listener to multiple elements Explanation: Event delegation is a technique that allows you to attach a single event listener to a parent element to handle events for multiple child elements.

Which method is used to add a new CSS class to an element in JavaScript?

a) element.classList.add()

b) element.style.add()

c) element.addClass()

d) element.className.add()

**Answer: a) element.classList.add() Explanation: The classList.add() method is used to add a new class to an element.

In the “Highlight List Items” exercise, what event property is used to identify the clicked element?

a) event.target

b) event.currentTarget

c) event.srcElement

d) event.element

Answer: a) event.target Explanation: The target property of the event object refers to the element that triggered the event.

What is the purpose of the new Date() constructor in the Display Current Date and Time exercise?

A) To format a string

B) To create a new Date object representing the current date and time

C) To add a delay

D) To display an alert

Answer: B

Explanation: The new Date() constructor creates a new Date object that represents the current date and time.

Which method is used to convert the Date object to a readable string in the Display Current Date and Time exercise?

A) toString()

B) toDateString()

C) toLocaleString()

D) toUTCString()

Answer: C

Explanation: The toLocaleString() method converts the Date object to a string representing the date and time in a readable format.

Which HTML element is used to display the date and time in the Display Current Date and Time exercise?

A) <div>

B) <p>

C) <span>

D) <h1>

Answer: B

Explanation: The <p> element with the ID dateTimeDisplay is used to display the date and time.

What triggers the display of the current date and time in the Display Current Date and Time exercise?

A) Hovering over the button

B) Clicking the button

C) Double-clicking the button

D) Loading the page

Answer: B

Explanation: Clicking the button with the ID showDateTimeButton triggers the display of the current date and time.

What happens when the changeTextButton is clicked in the Change Text Content exercise?

A) The text in the paragraph is changed to the input value

B) The button text is changed

C) The input field is cleared

D) The paragraph is hidden

Answer: A

Explanation: Clicking the changeTextButton updates the text content of the paragraph with the ID textDisplay to the value entered in the input field.

Which HTML element captures the user’s input in the Change Text Content exercise?

A) <textarea>

B) <input>

C) <button>

D) <div>

Answer: B

Explanation: The <input> element with the ID textInput captures the user’s input.

What method is used to update the text content of an element in the Change Text Content exercise?

A) innerHTML

B) innerText

C) textContent

D) value

Answer: C

Explanation: The textContent property is used to update the text content of the paragraph element.

What is the purpose of event delegation in the Highlight List Items exercise?

A) To handle multiple event listeners for each list item

B) To handle the click event on the entire list

C) To style the list items

D) To create new list items

Answer: B

Explanation: Event delegation is used to handle the click event on the entire list (<ul> element) instead of attaching event listeners to each individual list item.

Which CSS class is added to a list item when it is clicked in the Highlight List Items exercise?

A) selected

B) active

C) highlight

D) clicked

Answer: C

Explanation: The highlight class is added to a clicked list item to change its background color.

What does the JavaScript code do to ensure only one list item is highlighted at a time in the Highlight List Items exercise?

A) It toggles the highlight class on the clicked item

B) It adds the highlight class to the clicked item

C) It removes the highlight class from all items before adding it to the clicked item

D) It changes the text color of the clicked item

Answer: C

Explanation: The code first removes the highlight class from all list items and then adds it to the clicked item to ensure only one item is highlighted at a time.

Toggle Dark Mode

Description:

In this exercise, students will create a webpage with a button that toggles between light and dark modes. This exercise introduces changing CSS styles dynamically based on user interaction.

Topics Covered:

  • HTML structure
  • CSS styling
  • JavaScript event listeners
  • DOM manipulation (changing styles)

HTML:

<!DOCTYPE html>

<html lang=”en”>

<head>

    <meta charset=”UTF-8″>

    <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>

    <title>Toggle Dark Mode</title>

    <link rel=”stylesheet” href=”styles.css”>

</head>

<body>

    <button id=”toggleButton”>Toggle Dark Mode</button>

    <script src=”script.js”></script>

</body>

</html>

CSS:

body {

    font-family: Arial, sans-serif;

    display: flex;

    justify-content: center;

    align-items: center;

    height: 100vh;

    margin: 0;

    background-color: white;

    color: black;

    transition: background-color 0.3s, color 0.3s;

}

button {

    padding: 10px 20px;

    font-size: 16px;

    cursor: pointer;

}

body.dark-mode {

    background-color: black;

    color: white;

}

JavaScript:

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

    document.body.classList.toggle(‘dark-mode’);

});

Filter List Items

Description:

In this exercise, students will create a webpage with an input field to filter list items. As the user types in the input field, the list will be filtered to show only the items that match the input. This exercise introduces filtering and searching within the DOM.

Topics Covered:

  • HTML structure
  • CSS styling
  • JavaScript event listeners
  • DOM manipulation (filtering elements)

HTML:

<!DOCTYPE html>

<html lang=”en”>

<head>

    <meta charset=”UTF-8″>

    <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>

    <title>Filter List Items</title>

    <link rel=”stylesheet” href=”styles.css”>

</head>

<body>

    <input type=”text” id=”filterInput” placeholder=”Filter items…”>

    <ul id=”itemList”>

        <li>Apple</li>

        <li>Banana</li>

        <li>Cherry</li>

        <li>Date</li>

        <li>Fig</li>

        <li>Grape</li>

    </ul>

    <script src=”script.js”></script>

</body>

</html>

CSS:

body {

    font-family: Arial, sans-serif;

    display: flex;

    flex-direction: column;

    align-items: center;

    height: 100vh;

    justify-content: center;

    margin: 0;

}

input {

    padding: 10px;

    font-size: 16px;

    margin-bottom: 10px;

}

ul {

    list-style-type: none;

    padding: 0;

}

li {

    font-size: 18px;

    margin: 5px 0;

}

JavaScript:

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

    const filter = this.value.toLowerCase();

    const items = document.querySelectorAll(‘#itemList li’);

    items.forEach(item => {

        if (item.textContent.toLowerCase().includes(filter)) {

            item.style.display = ”;

        } else {

            item.style.display = ‘none’;

        }

    });

});

Accordion Menu

Description:

In this exercise, students will create an accordion menu where clicking on a section header expands or collapses the content. This exercise introduces creating interactive menus using JavaScript.

Topics Covered:

  • HTML structure
  • CSS styling
  • JavaScript event listeners
  • DOM manipulation (show/hide elements)

HTML:

<!DOCTYPE html>

<html lang=”en”>

<head>

    <meta charset=”UTF-8″>

    <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>

    <title>Accordion Menu</title>

    <link rel=”stylesheet” href=”styles.css”>

</head>

<body>

    <div class=”accordion”>

        <div class=”accordion-item”>

            <div class=”accordion-header”>Section 1</div>

            <div class=”accordion-content”>Content for section 1.</div>

        </div>

        <div class=”accordion-item”>

            <div class=”accordion-header”>Section 2</div>

            <div class=”accordion-content”>Content for section 2.</div>

        </div>

        <div class=”accordion-item”>

            <div class=”accordion-header”>Section 3</div>

            <div class=”accordion-content”>Content for section 3.</div>

        </div>

    </div>

    <script src=”script.js”></script>

</body>

</html>

CSS:

body {

    font-family: Arial, sans-serif;

    display: flex;

    justify-content: center;

    align-items: center;

    height: 100vh;

    margin: 0;

}

.accordion {

    width: 300px;

}

.accordion-item {

    border: 1px solid #ccc;

    border-radius: 5px;

    margin-bottom: 10px;

}

.accordion-header {

    background-color: #f0f0f0;

    padding: 10px;

    cursor: pointer;

    font-weight: bold;

}

.accordion-content {

    display: none;

    padding: 10px;

}

JavaScript:

document.querySelectorAll(‘.accordion-header’).forEach(header => {

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

        const content = this.nextElementSibling;

        if (content.style.display === ‘block’) {

            content.style.display = ‘none’;

        } else {

            content.style.display = ‘block’;

        }

    });

});

Create a Modal Popup

Description:

In this exercise, students will create a modal popup that appears when a button is clicked and disappears when the close button inside the modal is clicked. This exercise introduces creating overlays and handling multiple events.

Topics Covered:

  • HTML structure
  • CSS styling
  • JavaScript event listeners
  • DOM manipulation (show/hide elements)

HTML:

<!DOCTYPE html>

<html lang=”en”>

<head>

    <meta charset=”UTF-8″>

    <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>

    <title>Modal Popup</title>

    <link rel=”stylesheet” href=”styles.css”>

</head>

<body>

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

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

        <div class=”modal-content”>

            <span id=”closeModalButton” class=”close”>&times;</span>

            <p>This is a modal popup!</p>

        </div>

    </div>

    <script src=”script.js”></script>

</body>

</html>

CSS:

body {

    font-family: Arial, sans-serif;

    display: flex;

    justify-content: center;

    align-items: center;

    height: 100vh;

    margin: 0;

}

button {

    padding: 10px 20px;

    font-size: 16px;

    cursor: pointer;

}

.modal {

    display: none;

    position: fixed;

    z-index: 1;

    left: 0;

    top: 0;

    width: 100%;

    height: 100%;

    background-color: rgba(0, 0, 0, 0.5);

    justify-content: center;

    align-items: center;

}

.modal-content {

    background-color: white;

    padding: 20px;

    border-radius: 5px;

    width: 300px;

    text-align: center;

}

.close {

    position: absolute;

    top: 10px;

    right: 10px;

    cursor: pointer;

    font-size: 24px;

}

JavaScript:

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

    document.getElementById(‘modal’).style.display = ‘flex’;

});

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

    document.getElementById(‘modal’).style.display = ‘none’;

});

Image Carousel

Description:

In this exercise, students will create a simple image carousel with next and previous buttons to navigate through the images. This exercise introduces manipulating the DOM to change displayed content based on user interaction.

Topics Covered:

  • HTML structure
  • CSS styling
  • JavaScript event listeners
  • DOM manipulation (changing image sources)

HTML:

<!DOCTYPE html>

<html lang=”en”>

<head>

    <meta charset=”UTF-8″>

    <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>

    <title>Image Carousel</title>

    <link rel=”stylesheet” href=”styles.css”>

</head>

<body>

    <div class=”carousel”>

        <button id=”prevButton”>&lt;</button>

        <img id=”carouselImage” src=”image1.jpg” alt=”Image Carousel”>

        <button id=”nextButton”>&gt;</button>

    </div>

    <script src=”script.js”></script>

</body>

</html>

CSS:

body {

    font-family: Arial, sans-serif;

    display: flex;

    justify-content: center;

    align-items: center;

    height: 100vh;

    margin: 0;

}

.carousel {

    display: flex;

    align-items: center;

    gap: 10px;

}

button {

    padding: 10px 20px;

    font-size: 16px;

    cursor: pointer;

}

JavaScript:

const images = [‘image1.jpg’, ‘image2.jpg’, ‘image3.jpg’];

let currentIndex = 0;

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

    currentIndex = (currentIndex === 0) ? images.length – 1 : currentIndex – 1;

    document.getElementById(‘carouselImage’).src = images[currentIndex];

});

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

    currentIndex = (currentIndex === images.length – 1) ? 0 : currentIndex + 1;

    document.getElementById(‘carouselImage’).src = images[currentIndex];

});

Countdown Timer

Description:

In this exercise, students will create a countdown timer that counts down from a specified number of seconds and displays an alert when the time is up. This exercise introduces working with timers in JavaScript.

Topics Covered:

  • HTML structure
  • CSS styling
  • JavaScript event listeners
  • Working with JavaScript timers (setInterval and clearInterval)

HTML:

<!DOCTYPE html>

<html lang=”en”>

<head>

    <meta charset=”UTF-8″>

    <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>

    <title>Countdown Timer</title>

    <link rel=”stylesheet” href=”styles.css”>

</head>

<body>

    <input type=”number” id=”timeInput” placeholder=”Enter seconds”>

    <button id=”startButton”>Start Countdown</button>

    <p id=”timerDisplay”>0</p>

    <script src=”script.js”></script>

</body>

</html>

CSS:

body {

    font-family: Arial, sans-serif;

    display: flex;

    flex-direction: column;

    align-items: center;

    height: 100vh;

    justify-content: center;

    margin: 0;

}

input {

    padding: 10px;

    font-size: 16px;

    margin-bottom: 10px;

}

button {

    padding: 10px 20px;

    font-size: 16px;

    cursor: pointer;

    margin-bottom: 20px;

}

p {

    font-size: 24px;

}

JavaScript:

let timer;

let countdown;

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

    clearInterval(timer);

    const timeInput = document.getElementById(‘timeInput’).value;

    countdown = parseInt(timeInput, 10);

    document.getElementById(‘timerDisplay’).textContent = countdown;

    timer = setInterval(function() {

        countdown–;

        document.getElementById(‘timerDisplay’).textContent = countdown;

        if (countdown <= 0) {

            clearInterval(timer);

            alert(‘Time is up!’);

        }

    }, 1000);

});

Multiple Choice Questions

What method is used to toggle a CSS class on an element in JavaScript?

a) addClass

b) removeClass

c) toggleClass

d) classList.toggle

Answer: d) classList.toggle Explanation: The classList.toggle method is used to add or remove a class from an element, depending on whether the class is already present.

In the Filter List Items exercise, which event is used to detect changes in the input field?

a) change

b) input

c) keyup

d) keydown

Answer: b) input Explanation: The input event is fired when the value of an <input>, <textarea>, or <select> element has been changed.

How can you select the next sibling element in the DOM using JavaScript?

a) previousElementSibling

b) nextElement

c) nextSibling

d) nextElementSibling

Answer: d) nextElementSibling Explanation: The nextElementSibling property returns the element immediately following the specified one in its parent’s children list, and null if the specified element has no following sibling.

In the Accordion Menu exercise, what is the initial display style of the accordion content?

a) block

b) inline

c) none

d) hidden

Answer: c) none Explanation: The initial display style of the accordion content is set to none, meaning the content is hidden by default.

What CSS property is commonly used to create smooth transitions when changing styles dynamically?

a) animation

b) transform

c) transition

d) duration

Answer: c) transition Explanation: The transition property is used to create smooth transitions when CSS property values change dynamically.

Toggle Dark Mode

What event listener is used to trigger the dark mode toggle in the Toggle Dark Mode exercise?

A) mouseover

B) click

C) dblclick

D) keydown

Answer: B

Explanation: The click event listener is used to trigger the dark mode toggle when the button is clicked.

Which CSS class is added to the body element to enable dark mode in the Toggle Dark Mode exercise?

A) dark

B) night-mode

C) dark-mode

D) dark-theme

Answer: C

Explanation: The CSS class dark-mode is added to the body element to enable dark mode.

What CSS property is changed to switch between light and dark modes in the Toggle Dark Mode exercise?

A) color

B) background-color

C) font-size

D) margin

Answer: B

Explanation: The background-color property is changed to switch between light and dark modes.

How does the transition effect in the CSS help in the Toggle Dark Mode exercise?

A) It changes the text color instantly

B) It smoothens the change of the background and text color

C) It increases the font size

D) It adds a delay before changing the color

Answer: B

Explanation: The transition effect smoothens the change of the background and text color, making the switch between light and dark modes more visually appealing.

Filter List Items

What JavaScript event is used to trigger the filtering of list items in the Filter List Items exercise?

A) click

B) input

C) change

D) mouseover

Answer: B

Explanation: The input event is used to trigger the filtering of list items as the user types in the input field.

What method is used to convert text to lowercase for comparison in the Filter List Items exercise?

A) toUpperCase()

B) toLowerCase()

C) trim()

D) substring()

Answer: B

Explanation: The toLowerCase() method is used to convert text to lowercase for case-insensitive comparison.

What happens to list items that do not match the filter input in the Filter List Items exercise?

A) They are deleted

B) Their text color changes

C) They are hidden

D) They are moved to the bottom of the list

Answer: C

Explanation: List items that do not match the filter input are hidden by setting their display property to none.

Accordion Menu

What CSS property is used to hide the accordion content initially in the Accordion Menu exercise?

A) visibility

B) opacity

C) display

D) overflow

Answer: C

Explanation: The display property is set to none to hide the accordion content initially.

What event listener is used to expand or collapse accordion sections in the Accordion Menu exercise?

A) mouseover

B) click

C) dblclick

D) focus

Answer: B

Explanation: The click event listener is used to expand or collapse accordion sections when the header is clicked.

How does the JavaScript code determine which accordion content to show or hide in the Accordion Menu exercise?

A) It uses a specific ID

B) It uses the nextElementSibling property

C) It uses a class name

D) It uses an attribute selector

Answer: B

Explanation: The nextElementSibling property is used to select the content element following the clicked header to show or hide it.

In the Modal Popup exercise, which method is used to display the modal?

a) display = ‘block’

b) display = ‘flex’

c) show()

d) visible = true

Answer: b) display = ‘flex’ Explanation: The modal is displayed using display = ‘flex’ to center it using Flexbox.

What method is used to navigate to the next image in the Image Carousel exercise?

a) nextImage()

b) next()

c) src = nextImage

d) addEventListener

Answer: d) addEventListener Explanation: The addEventListener method is used to handle the click event for navigating to the next image.

In the Countdown Timer exercise, which function is used to repeatedly execute code at set intervals?

a) setTimeout

b) setInterval

c) clearInterval

d) setTimer

Answer: b) setInterval Explanation: The setInterval function is used to repeatedly execute the code that updates the countdown timer.

How can you stop the countdown timer in the Countdown Timer exercise?

a) stop()

b) clearInterval()

c) endTimer()

d) reset()

**Answer: b) clearInterval()** **Explanation:** The clearInterval` function is used to stop the timer from continuing to execute.

In the Image Carousel exercise, what happens when the index of the current image exceeds the length of the image array?

a) The carousel stops.

b) The index is reset to 0.

c) The index remains the same.

d) An error is thrown.

Answer: b) The index is reset to 0. Explanation: When the index exceeds the length of the image array, it is reset to 0 to loop back to the first image.

What is the initial CSS display property value of the modal in the Create a Modal Popup exercise?

A) block

B) none

C) flex

D) inline

Answer: B

Explanation: The initial CSS display property value of the modal is none, meaning it is hidden by default.

What event triggers the modal to appear in the Create a Modal Popup exercise?

A) Mouseover

B) Click on the open modal button

C) Double-click

D) Mouse out

Answer: B

Explanation: Clicking the open modal button triggers the modal to appear.

Which CSS property makes the modal appear on top of other elements?

A) position: absolute

B) z-index: 1

C) visibility: visible

D) position: fixed

Answer: D

Explanation: The position: fixed property ensures the modal appears on top of other elements and remains in a fixed position relative to the viewport.

How is the modal closed in the Create a Modal Popup exercise?

A) By clicking outside the modal

B) By clicking the close button inside the modal

C) By pressing the Escape key

D) By double-clicking the modal

Answer: B

Explanation: The modal is closed by clicking the close button inside the modal.

What JavaScript array is used to store the images in the Image Carousel exercise?

A) pictures

B) photos

C) slides

D) images

Answer: D

Explanation: The array images is used to store the file names of the images for the carousel.

What happens when the next button is clicked in the Image Carousel exercise?

A) The next image is displayed

B) The previous image is displayed

C) The carousel stops

D) The first image is displayed

Answer: A

Explanation: Clicking the next button displays the next image in the carousel.

How is the current image index updated when the previous button is clicked in the Image Carousel exercise?

A) It increments by 1

B) It decrements by 1

C) It resets to 0

D) It sets to the last index

Answer: B

Explanation: Clicking the previous button decrements the current image index by 1, wrapping around to the last image if the index is 0.

Which element displays the current image in the Image Carousel exercise?

A) <div>

B) <span>

C) <img>

D) <p>

Answer: C

Explanation: The <img> element with the ID carouselImage displays the current image.

What JavaScript function is used to repeatedly execute the countdown in the Countdown Timer exercise?

A) setTimeout

B) setInterval

C) clearInterval

D) requestAnimationFrame

Answer: B

Explanation: The setInterval function is used to repeatedly execute the countdown every second.

What happens when the countdown reaches zero in the Countdown Timer exercise?

A) The timer resets

B) The timer stops and an alert is shown

C) The timer continues counting into negative numbers

D) The timer starts over from the initial value

Answer: B

Explanation: When the countdown reaches zero, the timer stops and an alert is shown indicating that the time is up.