Web-based Personal Journal JavaScript, HTML, CSS

👤 Sharing: AI
Okay, here's a basic web-based personal journal implemented using JavaScript, HTML, and CSS.  It includes functionality for adding new entries, viewing them, and (crudely) storing them in the browser's local storage.  I've added comments to explain each section.

**HTML (index.html)**

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Personal Journal</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>

    <header>
        <h1>My Personal Journal</h1>
    </header>

    <main>
        <section id="entry-form">
            <h2>New Entry</h2>
            <textarea id="new-entry-content" placeholder="Write your thoughts here..."></textarea>
            <button id="add-entry-button">Add Entry</button>
        </section>

        <section id="journal-entries">
            <h2>Journal Entries</h2>
            <div id="entries-container">
                <!-- Journal entries will be dynamically added here by JavaScript -->
            </div>
        </section>
    </main>

    <footer>
        <p>&copy; 2024 My Journal</p>
    </footer>

    <script src="script.js"></script>
</body>
</html>
```

**CSS (style.css)**

```css
body {
    font-family: sans-serif;
    margin: 0;
    padding: 0;
    background-color: #f4f4f4;
    color: #333;
}

header {
    background-color: #333;
    color: #fff;
    padding: 1rem 0;
    text-align: center;
}

main {
    padding: 1rem;
    max-width: 800px;
    margin: 0 auto;
}

#entry-form {
    margin-bottom: 1rem;
    padding: 1rem;
    background-color: #fff;
    border-radius: 5px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

#entry-form textarea {
    width: 100%;
    height: 150px;
    padding: 0.5rem;
    margin-bottom: 0.5rem;
    border: 1px solid #ccc;
    border-radius: 4px;
    box-sizing: border-box; /* Important to include padding/border in the width/height */
}

#entry-form button {
    background-color: #5cb85c;
    color: #fff;
    padding: 0.5rem 1rem;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

#journal-entries {
    padding: 1rem;
    background-color: #fff;
    border-radius: 5px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.journal-entry {
    border-bottom: 1px solid #eee;
    padding-bottom: 0.5rem;
    margin-bottom: 0.5rem;
}

.journal-entry:last-child {
    border-bottom: none;
}

footer {
    text-align: center;
    padding: 1rem 0;
    background-color: #333;
    color: #fff;
    position:fixed;
    width:100%;
    bottom:0;
}
```

**JavaScript (script.js)**

```javascript
document.addEventListener('DOMContentLoaded', function() { // Wait for the document to load

    const entryContentInput = document.getElementById('new-entry-content');
    const addEntryButton = document.getElementById('add-entry-button');
    const entriesContainer = document.getElementById('entries-container');

    // Function to load entries from local storage
    function loadEntries() {
        const entries = JSON.parse(localStorage.getItem('journalEntries') || '[]'); // Get entries from local storage, or initialize to an empty array if none exist.  Crucially, parse the JSON.
        entries.forEach(entry => addEntryToUI(entry));  // Display each entry in the UI.
    }

    // Function to add a new entry to the UI
    function addEntryToUI(entryText) {
        const entryDiv = document.createElement('div');
        entryDiv.classList.add('journal-entry');
        entryDiv.textContent = entryText;
        entriesContainer.appendChild(entryDiv);
    }

    // Function to save entries to local storage
    function saveEntry(entryText) {
        const entries = JSON.parse(localStorage.getItem('journalEntries') || '[]'); // Get existing entries
        entries.push(entryText); // Add the new entry
        localStorage.setItem('journalEntries', JSON.stringify(entries)); // Save the updated array back to local storage as JSON
    }


    // Event listener for the "Add Entry" button
    addEntryButton.addEventListener('click', function() {
        const entryText = entryContentInput.value.trim(); // Get the text, remove leading/trailing whitespace

        if (entryText !== '') {
            addEntryToUI(entryText);  // Add the entry to the display
            saveEntry(entryText);    // Save the entry to local storage
            entryContentInput.value = ''; // Clear the input field
        } else {
            alert('Please enter some text for your journal entry.');
        }
    });

    // Load existing entries when the page loads
    loadEntries();

});
```

Key improvements and explanations:

* **`DOMContentLoaded`:**  The JavaScript code is wrapped in `document.addEventListener('DOMContentLoaded', function() { ... });`.  This is *crucial*.  It ensures that the JavaScript code only runs *after* the HTML document has been fully parsed and loaded.  Without this, your JavaScript code might try to access HTML elements that don't exist yet.

* **Local Storage:** Uses `localStorage` to persist the journal entries even after the browser is closed and reopened.  `localStorage` stores data as strings, so you need to use `JSON.stringify()` to convert the JavaScript array to a string when saving, and `JSON.parse()` to convert the string back to a JavaScript array when loading.

* **Error Handling (Empty Entries):**  Added a check in the `addEntryButton` click handler to prevent saving empty entries.

* **Clear Input:** The input field is cleared after a new entry is added.

* **`trim()`:**  The `.trim()` method is used to remove leading and trailing whitespace from the input text. This prevents empty entries from being added if the user just types spaces.

* **CSS Styling:** Added basic CSS to make the journal look a little nicer.  Includes a footer that stays at the bottom of the window.

* **Comments:**  Added more detailed comments to explain the purpose of each part of the code.

* **Well-Structured HTML:**  Uses `<header>`, `<main>`, `<section>`, and `<footer>` elements to structure the HTML content, making it more semantic and easier to understand.

* **`box-sizing: border-box`:** Very important CSS property to include padding and borders in the width and height of the `textarea`.

How to run it:

1.  **Save the files:** Save the HTML as `index.html`, the CSS as `style.css`, and the JavaScript as `script.js` in the *same* directory.
2.  **Open in Browser:** Open `index.html` in your web browser.

Now you should have a very basic, functional web-based journal that saves entries in your browser's local storage. Remember that `localStorage` is specific to the domain (your computer in this case), so the data won't be shared across different computers or browsers.
👁️ Viewed: 9

Comments