JavaScript Event Handling and Storage Solutions

Understanding the Problem

We need to implement several interactive features on a webpage that involve:

1. Event handling (click events)

2. DOM manipulation (adding/removing classes, changing content)

3. Browser storage (cookies and localStorage)

4. API integration (dictionary API)

Devising a Plan

1. Set up event listener for DOM content loaded

2. Implement click event handlers for each interactive element

3. Create functions for DOM manipulation

4. Implement storage functionality

5. Add API fetch functionality

Basic Solution Implementation

    window.addEventListener("DOMContentLoaded", () => {
        // Problem 1: Make circle blue
        const blueButton = document.getElementById('make-circle-blue');
        const blueCircle = document.getElementById('blue-border-circle');
        
        blueButton.addEventListener('click', () => {
            blueCircle.classList.add('blue-fill');
        });

        // Problem 2: Prevent checkbox checking
        const checkbox = document.getElementById('will-not-check');
        checkbox.addEventListener('click', (e) => {
            e.preventDefault();
        });

        // Problem 3: Banana status
        const bananaButton = document.getElementById('change-bananas-status');
        const bananaDiv = document.getElementById('bananas-div');
        const bananaImageDiv = document.getElementById('bananas-image-div');

        bananaButton.addEventListener('click', () => {
            bananaDiv.innerHTML = 'No Bananas Today!';
            
            if (!bananaImageDiv.querySelector('img')) {
                const img = document.createElement('img');
                img.src = './images/no-bananas.png';
                bananaImageDiv.appendChild(img);
            }
        });

        // Problem 4: Cookie storage
        const cookieInput = document.getElementById('fav-cookie');
        const cookieButton = document.getElementById('store-cookie');
        
        // Load saved cookie on page load
        const savedCookie = document.cookie
            .split('; ')
            .find(row => row.startsWith('favCookie='));
        if (savedCookie) {
            cookieInput.value = savedCookie.split('=')[1];
        }

        cookieButton.addEventListener('click', () => {
            // Set cookie with 30-minute expiration
            const expireTime = new Date(Date.now() + 30 * 60000).toUTCString();
            document.cookie = `favCookie=${cookieInput.value};expires=${expireTime}`;
        });

        // Problem 5: Pie list
        const pieInput = document.getElementById('pie-type');
        const pieButton = document.getElementById('save-pie');
        const pieList = document.querySelector('.pie-list');

        pieButton.addEventListener('click', () => {
            const pieValue = pieInput.value.trim();
            if (pieValue && pieList.children.length < 5) {
                const li = document.createElement('li');
                li.textContent = pieValue;
                pieList.appendChild(li);
                pieInput.value = '';
            }
        });

        // Problem 6: Local storage
        const iceCreamInput = document.getElementById('fav-ice-cream');
        const iceCreamButton = document.getElementById('save-ice-cream');
        
        // Load saved flavor
        const savedFlavor = localStorage.getItem('favIceCream');
        if (savedFlavor) {
            iceCreamInput.value = savedFlavor;
        }

        iceCreamButton.addEventListener('click', () => {
            localStorage.setItem('favIceCream', iceCreamInput.value);
        });

        // Problem 7: Fruit basket
        const appleButton = document.getElementById('add-apple');
        const orangeButton = document.getElementById('add-orange');
        const resetButton = document.getElementById('reset-basket');
        const fruitStorage = document.getElementById('fruit-storage');
        const totalFruit = document.getElementById('total-fruit');
        
        let fruitCount = 0;

        function updateFruitCount() {
            totalFruit.textContent = fruitCount;
        }

        function addFruit(fruit) {
            if (fruitCount < 25) {
                fruitStorage.textContent += fruit;
                fruitCount++;
                updateFruitCount();
            }
        }

        appleButton.addEventListener('click', () => addFruit('🍎'));
        orangeButton.addEventListener('click', () => addFruit('🍊'));
        resetButton.addEventListener('click', () => {
            fruitStorage.textContent = '';
            fruitCount = 0;
            updateFruitCount();
        });

        // Problem 8: Stop bubbles
        const bubbleButton = document.getElementById('bubble-maker');
        bubbleButton.addEventListener('click', (e) => {
            e.stopPropagation();
        });

        // Problem 9: Dictionary API
        const dictionaryButton = document.getElementById('dictionary-fetch');
        const resultsArea = document.getElementById('results-area');

        dictionaryButton.addEventListener('click', async () => {
            try {
                const response = await fetch('https://api.dictionaryapi.dev/api/v2/entries/en/dictionary');
                const data = await response.json();
                
                const word = data[0].word;
                const definition = data[0].meanings[0].definitions[0].definition;

                resultsArea.innerHTML = `
                <strong>Display Data Below:</strong>
                <ul>
                    <li>Word: ${word}</li>
                    <li>Definition: ${definition}</li>
                </ul>
                `;
            } catch (error) {
                console.error('Error fetching dictionary data:', error);
            }
        });
    });
    

Code Explanation

Let's break down each major component:

Event Handling

We wrap all our code in a DOMContentLoaded event listener to ensure the HTML elements exist before we try to interact with them. This is like waiting for all the ingredients to be on the counter before starting to cook.

DOM Manipulation

We use methods like classList.add() to modify elements, createElement() to make new elements, and appendChild() to add them to the page. Think of this like adding or removing items from a shelf in a store.

Storage

We use two types of storage:

1. Cookies: Temporary storage that expires (like writing a note that will self-destruct)

2. localStorage: Permanent storage (like writing in a diary that stays until explicitly erased)

API Integration

We use fetch() to get data from the dictionary API, similar to asking a librarian to look up a word in a dictionary and bring back the definition.

Real-World Applications

These concepts are used in:

- Shopping carts (storing items)

- User preferences (remembering settings)

- Social media interactions (handling clicks and updates)

- Form validation (preventing invalid submissions)

Alternative Solutions

More advanced approaches could include:

1. Using event delegation for multiple similar elements

2. Implementing a state management system

3. Using async/await for all asynchronous operations

4. Adding error handling and validation

Testing the Solution

To verify the solution:

1. Click each interactive element to ensure it responds correctly

2. Check that stored data persists after page reload

3. Verify that error cases are handled gracefully

4. Test edge cases like empty inputs and maximum limits