16.4 Programming Activity (20 mins)
Step-by-Step Activity:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dynamic Text and Style</title> </head> <body> <h1 id="heading">Hello, Welcome to My Web Page!</h1> <p id="description">This is a paragraph that will be updated.</p> <select id="Season"> <option>Winter</option> <option>Spring</option> <option>Summer</option> <option>Autumn</option> </select> <p id="results"></p> <!-- Button to change the heading text and style --> <button id="changeTextButton">Change Text and Style</button> <!-- Button to change the background color --> <button id="changeBackgroundButton">Change Background Color</button> <script> // Change text and style of the heading and paragraph let heading = document.getElementById("heading"); let paragraph = document.getElementById("description"); let changeTextButton = document.getElementById("changeTextButton"); const selectSeason = document.getElementById("Season"); const selectedParagraph = document.getElementById("results"); // Add an event listener to the select element selectSeason.addEventListener("change", function () { const selectedValue = selectSeason.value; // Set the text content of the paragraph selectedParagraph.textContent = selectedValue; // Set the background color based on the selected value selectedParagraph.style.backgroundColor = getBackgroundColor(selectedValue); }); function getBackgroundColor(season) { switch (season) { case "Winter": return "lightblue"; case "Spring": return "lightgreen"; case "Summer": return "yellow"; case "Autumn": return "orange"; default: return "white"; } } changeTextButton.addEventListener("click", function() { heading.innerText = "Text and Style Changed!"; heading.style.color = "blue"; // Change heading color to blue heading.style.fontSize = "30px"; // Change heading font size paragraph.innerText = "The paragraph text has been updated and styled."; paragraph.style.fontStyle = "italic"; // Change paragraph text to italic paragraph.style.color = "green"; // Change paragraph text color to green }); // Change the background color of the page let changeBackgroundButton = document.getElementById("changeBackgroundButton"); changeBackgroundButton.addEventListener("click", function() { document.body.style.backgroundColor = "lightblue"; // Change background color }); </script> </body> </html>
Explanation:
Run the file in a browser:
Challenge:
Activity Follow-up Questions:
Expected Outcome:
Last updated