Social Media Project: Signup, Login, and Post Management

Introduction

In this project, we will build a social media-like application where users can sign up, log in, create posts, edit their posts, and delete their posts. This project will cover HTML for structure, CSS for styling, and JavaScript for dynamic functionality.

Technologies Used

  • HTML

  • CSS

  • JavaScript (DOM manipulation, events, local storage)

Goals

  1. User Authentication:

    • Implement signup and login functionality.

    • Store user credentials securely.

  2. Post Management:

    • Allow users to create new posts.

    • Enable users to edit their existing posts.

    • Provide functionality to delete their posts.

  3. Data Persistence:

    • Utilize local storage to store posts and user authentication data.

Step-by-Step Implementation

HTML Structure (index.html)
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Home</title>
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body>
    <div id="homePage" class="hidden">
      <h1>Welcome, <span id="usernameDisplay"></span>!</h1>
      <div style="display: flex">
        <textarea
          id="postContent"
          placeholder="What's on your mind?"
        ></textarea>
        <button id="postBtn">Post</button>
      </div>
      <h2>Your Posts</h2>
      <div id="posts"></div>
    </div>
    <script src="app.js"></script>
  </body>
</html>
CSS Styles (styles.css)
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f0f0f0;
}

.hidden {
  display: none;
}

form {
  display: flex;
  flex-direction: column;
}

input,
textarea,
button {
  margin: 10px 0;
  padding: 10px;
  font-size: 16px;
}

#posts {
  margin-top: 20px;
}

.post {
  border: 1px solid #ccc;
  padding: 10px;
  margin-bottom: 10px;
}

.actions button {
  margin-right: 5px;
}
JavaScript Functionality (app.js)
// Check if a user is logged in
const currentUser = JSON.parse(localStorage.getItem("currentUser"));

if (!currentUser) {
  window.location.href = "./login.html";
}

// Function to display posts
function displayPosts() {
  const postsSection = document.getElementById("posts");
  postsSection.innerHTML = "";

  if (currentUser && currentUser.posts) {
    currentUser.posts.forEach((post, index) => {
      const postElement = document.createElement("div");
      postElement.classList.add("post");
      postElement.innerHTML = `
                <p class="author">Posted by: ${post.author}</p>
                <p class="content">${post.content}</p>
                <p class="timestamp">Posted at: ${post.createdAt}</p>
                <div class="actions">
                    <button onclick="editPost(${index})">Edit</button>
                    <button onclick="deletePost(${index})">Delete</button>
                </div>
            `;
      postsSection.appendChild(postElement);
    });
  }
}

// Function to handle post creation
document.getElementById("postBtn")?.addEventListener("click", function () {
  const content = document.getElementById("postContent").value.trim();

  if (!content) {
    alert("Please enter some content for your post.");
    return;
  }

  setTimeout(() => {
    const post = {
      author: currentUser.username,
      content: content,
      createdAt: new Date().toLocaleString(),
    };

    currentUser.posts.unshift(post);
    localStorage.setItem("currentUser", JSON.stringify(currentUser));

    document.getElementById("postContent").value = "";
    displayPosts();
  }, 1000);
});

// Function to handle post editing
function editPost(index) {
  const newContent = prompt(
    "Edit your post:",
    currentUser.posts[index].content
  );
  if (newContent !== null) {
    currentUser.posts[index].content = newContent;
    localStorage.setItem("currentUser", JSON.stringify(currentUser));
    displayPosts();
  }
}

// Function to handle post deletion
function deletePost(index) {
  if (confirm("Are you sure you want to delete this post?")) {
    currentUser.posts.splice(index, 1);
    localStorage.setItem("currentUser", JSON.stringify(currentUser));
    displayPosts();
  }
}

// On home page load, display posts and username
if (document.getElementById("homePage")) {
  document.getElementById("homePage").classList.remove("hidden");
  document.getElementById("usernameDisplay").textContent = currentUser.username;
  displayPosts();
}
HTML Structure (login.html)
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Login</title>
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body>
    <div id="loginPage">
      <h1>Login</h1>
      <form id="loginForm">
        <input type="text" id="username" placeholder="Username" required />
        <input type="password" id="password" placeholder="Password" required />
        <button type="submit">Login</button>
      </form>
      <p>Want to create an account, <a href="./signup.html">click here</a></p>
    </div>
    <script src="login.js"></script>
  </body>
</html>
JavaScript Functionality (login.js)
// Function to handle login
document
  .getElementById("loginForm")
  ?.addEventListener("submit", function (event) {
    event.preventDefault();

    const username = document.getElementById("username").value.trim();
    const password = document.getElementById("password").value;

    const storedUser = JSON.parse(localStorage.getItem("user"));

    if (
      storedUser &&
      storedUser.username === username &&
      storedUser.password === password
    ) {
      localStorage.setItem("currentUser", JSON.stringify(storedUser));
      alert("Login successful!");
      window.location.href = "index.html";
    } else {
      alert("Invalid username or password.");
    }
  });
Signup Structure (signup.html)
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Signup</title>
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body>
    <div id="signupPage">
      <h1>Signup</h1>
      <form id="signupForm">
        <input type="text" id="username" placeholder="Username" required />
        <input type="password" id="password" placeholder="Password" required />
        <input
          type="password"
          id="confirmPassword"
          placeholder="Confirm Password"
          required
        />
        <button type="submit">Signup</button>
      </form>
    </div>
    <script src="signup.js"></script>
  </body>
</html>
JavaScript Functionality (signup.js)
// Function to handle signup
document
  .getElementById("signupForm")
  ?.addEventListener("submit", function (event) {
    event.preventDefault();

    const username = document.getElementById("username").value.trim();
    const password = document.getElementById("password").value;
    const confirmPassword = document.getElementById("confirmPassword").value;

    if (!username || !password || !confirmPassword) {
      alert("Please fill in all fields.");
      return;
    }

    if (password.length < 8) {
      alert("Password must be at least 8 characters long.");
      return;
    }

    if (password !== confirmPassword) {
      alert("Passwords do not match.");
      return;
    }

    const user = { username, password, posts: [] };
    localStorage.setItem("user", JSON.stringify(user));

    alert("Account created successfully!");
    window.location.href = "login.html";
  });

Explanation

  • HTML: Defines the structure of the application with sections for signup, login, post creation, and post display.

  • CSS: Provides basic styling to improve the visual appeal and usability of the application.

  • JavaScript: Manages user authentication, post creation, editing, deletion, and persistence using local storage. It also handles UI updates based on the user's login status.

Notes for Students

  • User Authentication: Use local storage for storing user credentials temporarily. In a real-world scenario, implement server-side authentication for security.

  • Post Management: Practice DOM manipulation for creating, updating, and deleting posts dynamically.

  • Local Storage: Utilize local storage for storing posts persistently across page reloads.

This project enhances your understanding of web development concepts and provides practical experience in building interactive web applications. Feel free to customize and expand upon this project to further develop your skills. Happy coding!