본문 바로가기
개념/혼자 공부하는 Javascript

chapter 7) localStroage

by kiseno 2024. 12. 18.
728x90
반응형
SMALL
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const p = document.querySelector('p')
            const input = document.querySelector('input')
            const button = document.querySelector('button')

            const savedValue = localStorage.getItem('input')
            if(savedValue){
                input.value = savedValue
                p.textContent = `last value : ${savedValue}`
            }

            input.addEventListener('keyup', (event) => {
                const value = event.currentTarget.value
                localStorage.setItem('input', value)
            })

            button.addEventListener('click', (event) => {
                localStorage.clear()
                input.value = ''
            })
        })
    </script>
</head>
<body>
    <p></p>
    <button>delete</button>
    <input type = "text">
</body>
</html>

### How It Works

- **DOMContentLoaded**: The script waits for the DOM to fully load before querying elements and attaching event listeners, ensuring that the elements exist when the script tries to interact with them.

- **Querying Elements**: It selects a paragraph (`<p>`), an input field (`<input>`), and a button (`<button>`) from the DOM for later manipulation.

- **Retrieving and Displaying Saved Value**: 
  - It attempts to retrieve a saved value from `localStorage` using `localStorage.getItem('input')`. The key `'input'` is assumed to be used previously for storing the value of the input field.
  - If a saved value exists (`savedValue`), it updates the input field's value and sets the paragraph's text to indicate the last saved value. This provides immediate feedback to the user about the previously entered value upon reloading or revisiting the page.

- **Storing Input Value on Keyup**: 
  - An event listener is added to the input field to trigger on the `keyup` event, which fires every time the user releases a key while the input field is focused.
  - Inside this event handler, it retrieves the current value of the input field and stores it in `localStorage` using `localStorage.setItem('input', value)`. This effectively updates the stored value with every key release, ensuring the most recent input is saved.

- **Clearing Stored Data**: 
  - Another event listener is attached to the button for the `click` event.
  - When the button is clicked, it executes `localStorage.clear()`, which removes all data stored in `localStorage` for the origin, clearing the saved input value. Additionally, it resets the input field's value to an empty string as a visual indication that the stored data has been cleared.

### Practical Use

This script is a basic demonstration of using `localStorage` to make web applications more user-friendly by remembering user input or preferences across page reloads and browser sessions. The ability to clear stored data is also crucial for providing users with control over their data and ensuring privacy.

### Enhancements

For a real-world application, consider the following enhancements:

- **Scoped Clearing**: Instead of using `localStorage.clear()`, which removes all data, you might want to use `localStorage.removeItem('input')` to specifically clear only the stored input data. This prevents unintentionally clearing other unrelated data stored in `localStorage`.
  
- **UI Feedback**: Provide immediate visual feedback when the stored data is cleared, for example, by updating the paragraph's text content to indicate that no value is currently stored.

This script provides a foundational understanding of persisting and managing data in web applications, showcasing key functionalities provided by the Web Storage API.

728x90
반응형
LIST

'개념 > 혼자 공부하는 Javascript' 카테고리의 다른 글

chapter 7) handle to javascript code in HTML  (1) 2024.12.21
chapter 7) Keyboard event  (1) 2024.12.19
chapter 7) Manipulating  (1) 2024.12.17
chapter 7) select tag  (0) 2024.12.16
chapter 6) Add object properties dynamically  (1) 2024.12.15