Assignments Of Day 11: Event Handling in JavaScript

Rashmi Mishra
0

Assignments Of Day 11: Event Handling in JavaScript


Assignment 1: Button Click Event

Task:
Create a button with the text "Click Me!" that, when clicked, changes the background color of the page to lightblue.

Solution:

html

Copy code

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

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

    <title>Button Click Event</title>

</head>

<body>

    <button id="myButton">Click Me!</button>

 

    <script>

        const button = document.getElementById("myButton");

 

        button.addEventListener("click", function() {

            document.body.style.backgroundColor = "lightblue";

        });

    </script>

</body>

</html>

Explanation:

  • When the button is clicked, the background color of the body element changes to lightblue using the event listener attached to the button.

Assignment 2: Mouseover Event on Image

Task:
Create an image element that changes the image source when the user hovers over the image. For this, you will need two images: one for the default image and one for the hover image.

Solution:

html

Copy code

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

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

    <title>Mouseover Event</title>

</head>

<body>

    <img id="myImage" src="image1.jpg" alt="Image" width="300">

 

    <script>

        const img = document.getElementById("myImage");

 

        img.addEventListener("mouseover", function() {

            img.src = "image2.jpg";  // Change to hover image

        });

 

        img.addEventListener("mouseout", function() {

            img.src = "image1.jpg";  // Revert to default image

        });

    </script>

</body>

</html>

Explanation:

  • The mouseover event changes the image source when the user hovers over the image.
  • The mouseout event resets the image source when the mouse moves away.

Assignment 3: Keydown Event

Task:
Create an event listener that listens for keydown events. When a key is pressed, it should display the name of the key pressed in a <p> element.

Solution:

html

Copy code

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

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

    <title>Keydown Event</title>

</head>

<body>

    <p id="keyName">Press any key!</p>

 

    <script>

        const keyNameDisplay = document.getElementById("keyName");

 

        document.addEventListener("keydown", function(event) {

            keyNameDisplay.textContent = "Key pressed: " + event.key;

        });

    </script>

</body>

</html>

Explanation:

  • The keydown event listens for any keypress on the document.
  • The pressed key is displayed in the paragraph element with the ID keyName.

Assignment 4: Form Submit Event

Task:
Create a form with a text input and a submit button. When the user submits the form, prevent the form from being submitted, and display a message saying "Form submission prevented".

Solution:

html

Copy code

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

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

    <title>Form Submit Event</title>

</head>

<body>

    <form id="myForm">

        <input type="text" id="username" placeholder="Enter your name">

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

    </form>

 

    <script>

        const form = document.getElementById("myForm");

 

        form.addEventListener("submit", function(event) {

            event.preventDefault();  // Prevents the form from being submitted

            alert("Form submission prevented");

        });

    </script>

</body>

</html>

Explanation:

  • The submit event is triggered when the user clicks the submit button.
  • The event.preventDefault() method is used to prevent the form from being submitted, and an alert is shown instead.

Assignment 5: Event Propagation (Capturing and Bubbling)

Task:
Create a nested <div> structure where the outer div and the inner div both have a click event listener. The outer div should use event capturing (true), and the inner div should use event bubbling (false).

Solution:

html

Copy code

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

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

    <title>Event Propagation</title>

</head>

<body>

    <div id="outerDiv" style="width: 300px; height: 300px; background-color: lightgreen;">

        Outer Div

        <div id="innerDiv" style="width: 100px; height: 100px; background-color: lightcoral; margin: 50px;">

            Inner Div

        </div>

    </div>

 

    <script>

        const outerDiv = document.getElementById("outerDiv");

        const innerDiv = document.getElementById("innerDiv");

 

        // Event listener with capturing phase (true)

        outerDiv.addEventListener("click", function() {

            console.log("Outer div clicked (capturing phase)");

        }, true);

 

        // Event listener with bubbling phase (false)

        innerDiv.addEventListener("click", function() {

            console.log("Inner div clicked (bubbling phase)");

        }, false);

    </script>

</body>

</html>

Explanation:

  • The outer div listens for clicks during the capturing phase (because true is passed), while the inner div listens during the bubbling phase (because false is passed).
  • When both divs are clicked, the output will show that the outer div is logged first, followed by the inner div, demonstrating the order of event propagation.

Assignment 6: Hover and Click Event Combination

Task:
Create a <div> that changes its background color to yellow when hovered over, and then changes it to green when clicked.

Solution:

html

Copy code

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

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

    <title>Hover and Click Event</title>

</head>

<body>

    <div id="colorBox" style="width: 200px; height: 200px; background-color: lightgrey;">

        Hover or Click me!

    </div>

 

    <script>

        const colorBox = document.getElementById("colorBox");

 

        // Mouseover event

        colorBox.addEventListener("mouseover", function() {

            colorBox.style.backgroundColor = "yellow";

        });

 

        // Mouseout event

        colorBox.addEventListener("mouseout", function() {

            colorBox.style.backgroundColor = "lightgrey";

        });

 

        // Click event

        colorBox.addEventListener("click", function() {

            colorBox.style.backgroundColor = "green";

        });

    </script>

</body>

</html>

Explanation:

  • The mouseover event changes the background color to yellow when the user hovers over the <div>.
  • The mouseout event reverts the color to light grey when the mouse leaves the element.
  • The click event changes the background color to green when the element is clicked.

These assignments cover a wide range of concepts, including clickmouseoverkeydownsubmitevent propagation, and event handling techniques in JavaScript, allowing students to practice and understand event handling in different scenarios.

4o mini

You said:

some more

ChatGPT said:

ChatGPT

Here are more assignments with solutions based on Event Handling in JavaScript.


Assignment 7: Toggle Text on Button Click

Task:
Create a button that toggles the visibility of a paragraph when clicked. Initially, the paragraph should be visible, and clicking the button should hide the paragraph. Clicking the button again should show the paragraph.

Solution:

html

Copy code

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

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

    <title>Toggle Text</title>

</head>

<body>

    <button id="toggleButton">Toggle Text</button>

    <p id="text">This is a paragraph that can be hidden or shown.</p>

 

    <script>

        const button = document.getElementById("toggleButton");

        const text = document.getElementById("text");

 

        button.addEventListener("click", function() {

            if (text.style.display === "none") {

                text.style.display = "block";

            } else {

                text.style.display = "none";

            }

        });

    </script>

</body>

</html>

Explanation:

  • The button's click event is used to toggle the display property of the paragraph.
  • Initially, the paragraph is visible, but clicking the button hides or shows it based on its current state.

Assignment 8: Change Image on Button Click

Task:
Create an image element that changes its source when the user clicks on a button. Display the original image first, and when the button is clicked, change it to another image.

Solution:

html

Copy code

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

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

    <title>Change Image</title>

</head>

<body>

    <img id="image" src="image1.jpg" alt="Image" width="300">

    <button id="changeImageButton">Change Image</button>

 

    <script>

        const image = document.getElementById("image");

        const button = document.getElementById("changeImageButton");

 

        button.addEventListener("click", function() {

            image.src = "image2.jpg";

        });

    </script>

</body>

</html>

Explanation:

  • Clicking the button changes the src attribute of the image element, thus changing the image.

Assignment 9: Changing Text Color on Hover

Task:
Create a paragraph that changes its text color to blue when hovered over and changes back to black when the mouse moves away.

Solution:

html

Copy code

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

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

    <title>Hover Text Color</title>

</head>

<body>

    <p id="text">Hover over this text to change its color!</p>

 

    <script>

        const text = document.getElementById("text");

 

        text.addEventListener("mouseover", function() {

            text.style.color = "blue";

        });

 

        text.addEventListener("mouseout", function() {

            text.style.color = "black";

        });

    </script>

</body>

</html>

Explanation:

  • The mouseover event changes the text color to blue, and the mouseout event changes it back to black when the mouse leaves the text.

Assignment 10: Form Validation on Submit

Task:
Create a form with a text input for entering a name. If the input is empty when the user submits the form, display an alert message saying "Please enter your name!". Prevent the form submission if the input is empty.

Solution:

html

Copy code

<!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>

</head>

<body>

    <form id="nameForm">

        <label for="name">Enter your name:</label>

        <input type="text" id="name" name="name">

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

    </form>

 

    <script>

        const form = document.getElementById("nameForm");

        const nameInput = document.getElementById("name");

 

        form.addEventListener("submit", function(event) {

            if (nameInput.value.trim() === "") {

                event.preventDefault();  // Prevent form submission

                alert("Please enter your name!");

            }

        });

    </script>

</body>

</html>

Explanation:

  • The form’s submit event checks if the input is empty.
  • If the input is empty, the form submission is prevented using event.preventDefault() and an alert message is shown.

Assignment 11: Stop Propagation of Click Event

Task:
Create two nested <div> elements. When the inner <div> is clicked, stop the event from propagating to the outer <div>, so the outer <div>’s click handler is not triggered.

Solution:

html

Copy code

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

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

    <title>Stop Event Propagation</title>

</head>

<body>

    <div id="outerDiv" style="width: 300px; height: 300px; background-color: lightgreen;">

        Outer Div

        <div id="innerDiv" style="width: 100px; height: 100px; background-color: lightcoral; margin: 50px;">

            Inner Div

        </div>

    </div>

 

    <script>

        const outerDiv = document.getElementById("outerDiv");

        const innerDiv = document.getElementById("innerDiv");

 

        outerDiv.addEventListener("click", function() {

            console.log("Outer div clicked");

        });

 

        innerDiv.addEventListener("click", function(event) {

            console.log("Inner div clicked");

            event.stopPropagation();  // Stop the click event from propagating to the outer div

        });

    </script>

</body>

</html>

Explanation:

  • The stopPropagation() method is used to stop the event from bubbling up to the outer div when the inner div is clicked.

Assignment 12: Prevent Form Submit on Button Click

Task:
Create a form with a submit button. Add an event listener to the submit button that prevents the form submission and displays a message saying "Form submission prevented!" when clicked.

Solution:

html

Copy code

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

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

    <title>Prevent Form Submit</title>

</head>

<body>

    <form id="myForm">

        <input type="text" placeholder="Enter your name" required>

        <button type="submit" id="submitButton">Submit</button>

    </form>

 

    <script>

        const form = document.getElementById("myForm");

        const submitButton = document.getElementById("submitButton");

 

        submitButton.addEventListener("click", function(event) {

            event.preventDefault();  // Prevent the form from being submitted

            alert("Form submission prevented!");

        });

    </script>

</body>

</html>

Explanation:

  • The submit button's click event is used to prevent form submission and show an alert instead, using event.preventDefault().

Assignment 13: Dynamic Button Creation with Event Handling

Task:
Create a button dynamically using JavaScript. When the button is clicked, display a message "Button Clicked!" on the page.

Solution:

html

Copy code

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

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

    <title>Dynamic Button Creation</title>

</head>

<body>

    <div id="message"></div>

 

    <script>

        const messageDiv = document.getElementById("message");

 

        // Create a new button dynamically

        const button = document.createElement("button");

        button.textContent = "Click Me";

        document.body.appendChild(button);

 

        // Add event listener to the dynamically created button

        button.addEventListener("click", function() {

            messageDiv.textContent = "Button Clicked!";

        });

    </script>

</body>

</html>

Explanation:

  • A button is created dynamically using document.createElement(), and an event listener is attached to it to display a message when clicked.

Post a Comment

0Comments

Post a Comment (0)