Showing posts with label Web Development. Show all posts

Web Dev Day 22: UI Styling & Vercel Deployment

📅 Date: June 27, 2026

🧠 Mood: The Publisher 🚀

🔥 Topic: Web Dev Day 22: UI Styling & Vercel Deployment

🌐 Going Live: CineMetrics Phase 1

Building a backend server and testing endpoints in Postman is satisfying, but nothing beats the feeling of a live URL. For the past three days, I have been locked into the terminal, establishing the architecture, writing MongoDB aggregation pipelines, and configuring the Fetch API. Today, I finally put a face on the data and shipped it to the web.

The goal for today was two-fold: First, transform the raw HTML structure into a clean, modern, dark-themed User Interface (UI). Second, deploy the frontend so anyone on the internet can interact with the analytics engine. Phase 1 of CineMetrics is officially complete and live.

Live Project Links:
🚀 Live Demo: cinemetrics-zeta.vercel.app
💻 Source Code: github.com/lamesahil/cinemetrics

🎨 CSS Architecture & UI Design

For the UI, I avoided heavy CSS frameworks like Tailwind or Bootstrap. I wanted to strengthen my raw CSS fundamentals. I focused heavily on CSS Variables (Custom Properties) to maintain a consistent dark mode theme and Flexbox for responsive layouts.

1. Mobile-First Responsiveness

Following SEO best practices, the UI is built with a Mobile-First approach. Using CSS Media Queries, the movie grid automatically reflows from a single column on mobile to three columns on desktop. A responsive design is non-negotiable for modern web applications.

2. Dynamic DOM Updates

The UI is entirely data-driven. When the Fetch API pulls the movie list and the aggregation data from the Node.js backend, JavaScript dynamically generates the HTML elements (Cards, Tags, and Analytics badges) and injects them into the DOM without requiring a page reload.


🚀 The Vercel Deployment Strategy

Localhost is safe, but production is where real engineering happens. I chose Vercel for the frontend deployment because of its seamless integration with GitHub.

  • CI/CD Pipeline: Vercel automatically tracks the main branch of my GitHub repository. Any time I execute a git push, Vercel detects the change, triggers a new build, and deploys the updated code instantly.
  • Environment Variables: The most critical step was updating the API_URL in my frontend code. On localhost, it pointed to http://localhost:5000. I had to ensure the production build points to the live backend server.

🎯 The Road to Phase 2

Seeing my own backend data dynamically populate a live, beautifully styled UI on a public URL is a massive milestone. Phase 1 of CineMetrics is complete. The foundation is solid. Next week, we begin Phase 2: Implementing JWT Authentication and turning this personal tracker into a social network. Time to rest the brain and prepare for the next sprint.

Web Dev Day 21: Vanilla JS API Integration

📅 Date: June 26, 2026

🧠 Mood: The Integrator 🔌

🔥 Topic: Web Dev Day 21: Vanilla JS API Integration

🌐 Bringing the Data to Life

An API is useless if users can't interact with it. Today, I moved into the cinemetrics-frontend directory to build the user interface. Before relying on heavy frameworks like React, it is crucial to understand how the browser natively communicates with servers.

I structured the dashboard using standard HTML5 and applied a dark-themed CSS stylesheet. The real magic, however, happened inside app.js, where I utilized the modern JavaScript Fetch API to bridge the gap between my UI and the Node.js server.


⚡ The Fetch API & DOM Manipulation

To display the top genre analytics we built yesterday, the frontend needs to make an asynchronous HTTP request to our backend, wait for the JSON response, and dynamically update the DOM.

// app.js - Frontend Integration
const API_URL = 'http://localhost:5000/api/movies';
const topGenreDisplay = document.getElementById('top-genre');

// Async function to fetch and display analytics
async function loadAnalytics() {
    try {
        // 1. Await the network request
        const response = await fetch(`${API_URL}/analytics`);
        
        // 2. Parse the JSON data
        const result = await response.json();
        
        // 3. Update the DOM securely
        if (result.success && result.data.length > 0) {
            const stats = result.data[0];
            topGenreDisplay.innerText = `Top Genre: ${stats._id} (${stats.count} watched)`;
        } else {
            topGenreDisplay.innerText = "Add more movies to see analytics!";
        }
    } catch (error) {
        console.error("Failed to connect to the CineMetrics Server", error);
        topGenreDisplay.innerText = "Error loading data.";
    }
}

// Trigger function on page load
document.addEventListener('DOMContentLoaded', loadAnalytics);

🛡️ Overcoming the CORS Error

The moment I tried to fetch data from my frontend (running on port 5500) to my backend (running on port 5000), the browser blocked it with a massive red CORS Policy error. Browsers block cross-origin requests for security reasons. I had to jump back into my server.js file and explicitly install and configure the cors middleware to allow my frontend to safely pull the data.


🎯 Phase 1 Complete

CineMetrics Phase 1 is officially live locally. The frontend seamlessly communicates with the database, proving the architecture works. As per the PRD, Phase 2 will introduce User Authentication (JWT) and social networking features. But for now, it's time to celebrate a successful deployment.

Web Dev Day 20: Express Backend & MongoDB Aggregation

📅 Date: June 25, 2026

🧠 Mood: The Data Wrangler 📊

🔥 Topic: Web Dev Day 20: Express Backend & MongoDB Aggregation

⚙️ Forging the Backend Engine

With the architecture set, today was all about wiring up the backend for CineMetrics. I initialized my package.json, installed Express and Mongoose, and secured my connection strings using environment variables (.env).

Building the basic CRUD endpoints (POST, GET, PATCH) was straightforward. The real engineering challenge was satisfying the analytics requirement of my PRD. I needed to extract the Top Genre and Average Rating from the database. Instead of pulling all the data into my Node.js server and filtering it with loops—which is terrible for performance—I utilized MongoDB Aggregation Pipelines to make the database do the heavy lifting.


🗄️ The Aggregation Pipeline

An aggregation pipeline processes data through multiple stages, passing the results from one stage directly into the next. Here is how I built the /api/movies/analytics endpoint controller.

// controllers/analyticsController.js
const Movie = require('../models/Movie');

exports.getAnalytics = async (req, res) => {
    try {
        const stats = await Movie.aggregate([
            // Stage 1: Filter out unwatched movies
            { $match: { isWatched: true } },
            
            // Stage 2: Deconstruct the genre array so each genre gets its own document
            { $unwind: "$genre" },
            
            // Stage 3: Group by genre, count them, and average the ratings
            { 
                $group: {
                    _id: "$genre",
                    count: { $sum: 1 },
                    avgRating: { $avg: "$rating" }
                }
            },
            
            // Stage 4: Sort by the most watched genre (descending)
            { $sort: { count: -1 } },
            
            // Stage 5: Only keep the absolute top genre
            { $limit: 1 }
        ]);

        res.status(200).json({ success: true, data: stats });
    } catch (error) {
        res.status(500).json({ success: false, error: "Server Error" });
    }
};

⚠️ Routing Hierarchy Warning

One massive bug I encountered was Endpoint Collision. I initially placed my /api/movies/:id route above my /api/movies/analytics route in the code. Express mistakenly thought the word "analytics" was a dynamic movie ID, causing a server crash. Remember to always place static routes above dynamic parameter routes!


🎯 Backend Secured

The RESTful API is now fully operational and securely handling complex data queries via Mongoose. Tomorrow, we open the cinemetrics-frontend folder to build the dashboard UI and connect it to our server using Vanilla JavaScript.

Web Dev Day 19: CineMetrics Architecture & PRD

📅 Date: June 24, 2026

🧠 Mood: The Architect 🏗️

🔥 Topic: Web Dev Day 19: CineMetrics Architecture & PRD

📐 Building Like a Software Engineer

After spending weeks grinding through complex recursion and Divide & Conquer algorithms, I needed to channel that logic into something tangible. As an engineering student, writing raw code is only half the battle. The real challenge is system design. Today, I officially kicked off my new Full-Stack project: CineMetrics.

CineMetrics is a movie analytics and tracking system. But instead of blindly opening VS Code and typing, I treated this like a professional industry project. I wrote a comprehensive Product Requirements Document (PRD) and established a strict decoupled architecture before writing a single line of JavaScript.


📂 The Decoupled Architecture

A massive mistake junior developers make is mixing their server code and UI code in the same folder. For CineMetrics, I established a strict boundary between the client and the server.

CineMetrics/
├── cinemetrics-backend/    # The Node.js / Express Server
│   ├── controllers/        # Business Logic
│   ├── models/             # Mongoose Schemas
│   ├── routes/             # API Endpoints
│   ├── CineMetrics_Detailed_PRD.md
│   └── server.js           # Entry Point
└── cinemetrics-frontend/   # The Vanilla JS / UI Client
    ├── index.html
    ├── style.css
    └── app.js              # Fetch API Logic

1. The Product Requirements (Phase 1)

According to my PRD, Phase 1 focuses strictly on core CRUD operations and data processing. Users must be able to add movies, update their watch status, and crucially, view data-driven analytics. The system will track total watched movies, calculate average ratings, and pinpoint the user's top genre.

2. The MongoDB Schema Design

The data model is clean and validated. Every movie requires a title and an array of genres. We also track a numerical rating (1-5) and a boolean isWatched flag. Proper schema validation at the database level prevents dirty data from breaking our analytics engine later.


🎯 What's Next?

The blueprint is finalized. Tomorrow, I dive into the cinemetrics-backend directory to set up the Express server and write the most complex part of Phase 1: The MongoDB Aggregation Pipeline for the analytics engine.

Web Dev Day 18: Unmasking JS (Prototypes)

📅 Date: April 25, 2026

🧠 Mood: The Mechanic 🔧

🔥 Topic: Web Dev Day 18: Unmasking JS (Prototypes)

🛑 JavaScript Lied to Me

It’s Saturday. Usually, I would be grinding out Linked Lists in C++ today. But my mind is completely stuck on what I learned yesterday about Object-Oriented Programming in JavaScript. I thought I understood it. I used the class keyword, I built a constructor, and it felt exactly like C++ or Java.

Then, I dug a little deeper and hit a brutal reality check: Classes in JavaScript are fake.

Unlike Java or C++, JavaScript does not have traditional classes. The class keyword introduced in ES6 is literally just "syntactic sugar"—a nice-looking wrapper put there to make developers from other languages feel comfortable. Under the hood, JavaScript is fundamentally a prototype-based language. If you don't understand prototypes, you don't understand JavaScript. Today, I opened the hood to see the actual engine.


🧬 The Prototype Chain (The DNA of JS)

In JavaScript, absolutely everything is an Object. Arrays are objects. Functions are objects. Strings are objects. And every single object has a hidden, built-in property called its Prototype. This prototype is like a parent object from which it inherits methods and properties.

1. How Inheritance Actually Works

When you create an array let arr = [1, 2, 3] and type arr.push(4), where did the .push() function come from? You didn't write it. JavaScript looks at your array, doesn't find a push method, so it travels UP the chain to the master Array.prototype object. It finds the method there and uses it.

2. The End of the Line (Null)

This lookup process goes up and up. Your array inherits from Array.prototype, which inherits from the ultimate master Object.prototype. If JavaScript looks for a method and reaches Object.prototype without finding it, it hits null and throws a terrifying "undefined" error.


💻 Practical: Hacking the Master Object

To prove I understood this, I decided to do something dangerous but educational. I injected a custom method directly into the highest-level JavaScript Object prototype. By doing this, every single variable I create instantly gains access to this new superpower.

// Let's create an array and a string
let myFriends = ["Munmun", "Rahul"];
let myName = "Sahil";

// We inject a brand new method straight into the core Object Prototype
Object.prototype.sahilCustomPrint = function() {
    console.log(`System Override: Executing Sahil's custom logic on ${this}`);
};

// Now, watch the magic. 
// Even though I never added this method to the array or the string directly...

myFriends.sahilCustomPrint(); 
// Output: System Override: Executing Sahil's custom logic on Munmun,Rahul

myName.sahilCustomPrint();    
// Output: System Override: Executing Sahil's custom logic on Sahil

Because both the Array and the String ultimately trace their ancestry back to the master Object, they both inherited my custom function automatically. This is incredibly powerful, but it's also why you should rarely mess with the global prototype in production—you might accidentally overwrite critical browser functions!


🎯 The Solid Foundation

Understanding Prototypes demystifies the "magic" of JavaScript. It proves that there is no magic, just a highly logical chain of object references. Tomorrow, I will tackle the final boss of core JavaScript concepts: Closures and Lexical Scoping. Let's finish the weekend strong.

Web Dev Day 17: Object-Oriented JS (The Blueprint)

📅 Date: April 24, 2026

🧠 Mood: The Engineer ⚙️

🔥 Topic: Web Dev Day 17: Object-Oriented JS (The Blueprint)

📐 Returning to Familiar Ground

Up to this point, I have been writing JavaScript in a very "procedural" way. Create a variable here, write a function there, attach an event listener. It works fine for small scripts like a Dark Mode toggle or a simple Crypto API fetch. But what happens when you are building a system with 1,000 users?

You cannot write 1,000 separate variables. You need a system. Having spent a significant amount of time grinding through data structures and algorithms in C++, the concept of structuring data is hardwired into my brain. Today, I finally brought that engineering mindset into the browser by diving into Object-Oriented Programming (OOP) in JavaScript. It is time to stop hardcoding data and start building blueprints.


🏭 Classes and the 'this' Keyword

Modern JavaScript (ES6) introduced the class syntax. It acts exactly like a factory template. Instead of creating a user from scratch every time, you define the "shape" of a user once, and then stamp out as many copies (objects) as you need.

1. The Constructor Method

Whenever you create a new object from your blueprint, a special function called the constructor() runs automatically. This is where you pass in the initial data—like the user's name or email—to set up that specific instance.

2. The Infamous 'this' Keyword

In JS, this points to the specific object that is currently executing the code. If I have two users, Sahil and Munmun, this.name will correctly point to "Sahil" when my object calls it, and "Munmun" when her object calls it, even though they share the exact same blueprint.


💻 Practical: Building the User Factory

Here is a clean implementation of a User class that encapsulates its own data and behavior (methods).

// 1. Define the Blueprint (Class)
class User {
    // The setup function
    constructor(username, role) {
        this.username = username;
        this.role = role;
        this.isOnline = false;
    }

    // A method (behavior) shared by all users
    login() {
        this.isOnline = true;
        console.log(`${this.username} has logged into the system.`);
    }

    // Checking status
    getStatus() {
        return `${this.username} is currently ${this.isOnline ? 'Online 🟢' : 'Offline 🔴'}`;
    }
}

// 2. Instantiate Objects using the 'new' keyword
const adminUser = new User("Sahil", "Admin");
const guestUser = new User("Munmun", "Guest");

// 3. Testing the logic
console.log(adminUser.getStatus()); // Sahil is currently Offline 🔴
adminUser.login();                  // Sahil has logged into the system.
console.log(adminUser.getStatus()); // Sahil is currently Online 🟢

// Notice how guestUser is unaffected by adminUser's actions
console.log(guestUser.getStatus()); // Munmun is currently Offline 🔴

The beauty of this is scalability. I can generate 10,000 users using a loop and that same User class, and my code remains incredibly clean and modular.


🎯 What's Next?

Classes in JavaScript are actually just "syntactic sugar" over something called Prototypal Inheritance. Tomorrow, I will dive deep into Prototypes to understand how JavaScript shares methods under the hood without wasting memory. The core JS deep dive continues!

Web Dev Day 16: LocalStorage vs SessionStorage

📅 Date: April 23, 2026

🧠 Mood: The Data Hoarder 🗄️

🔥 Topic: Web Dev Day 16: LocalStorage vs SessionStorage

😤 The Page Refresh Tragedy

Picture this: You are sitting on the train, filling out a massive, multi-page university form on your phone. The network drops just as you hit submit. The browser throws an error, you swipe down to refresh the page, and boom—every single text box is completely empty. You have to start all over again. The frustration is enough to make you want to throw your phone out the window.

As developers, we know that JavaScript variables are incredibly fragile. The moment a user hits the refresh button, or navigates away from the page, all the data held in JS variables is instantly destroyed. The slate is wiped clean. Today, I learned how to fix this terrible user experience by tapping into the browser's secret database: Web Storage.


🗄️ The 5MB Safe in Your Browser

Modern browsers give every website a tiny, isolated database (around 5MB) to store data directly on the user's device. It operates using simple Key-Value pairs (like a dictionary). There are two main types of storage, and choosing the wrong one can break your application.

1. LocalStorage (The Permanent Tattoo)

Data saved in localStorage does not expire. If you save a user's "Dark Mode" preference here, they can close the tab, shut down their laptop, and come back three months later—the website will still remember they prefer Dark Mode. It only goes away if the developer writes code to delete it, or the user manually clears their browser cache.

2. SessionStorage (The Sticky Note)

Data saved in sessionStorage is temporary. It survives page refreshes, but the absolute second the user closes the browser tab, the data is incinerated. This is perfect for sensitive data or temporary states, like a multi-step checkout form where you don't want old data lingering if they abandon the cart and come back tomorrow.


💻 Practical: Saving Theme Preferences

Back in Day 10, I built a Dark Mode toggle button. But it was flawed because it reset to Light Mode every time I refreshed the page. Today, I upgraded it using LocalStorage so it remembers the user's choice permanently. Here is the exact syntax:

// The 3 Core Commands of Web Storage:
// 1. setItem(key, value)
// 2. getItem(key)
// 3. removeItem(key)

// Example: Saving Dark Mode State

// When the page loads, check if they already have a saved preference
const savedTheme = localStorage.getItem("themePref");

if (savedTheme === "dark") {
    document.body.classList.add("dark-mode");
}

// When the user clicks the toggle button
toggleBtn.addEventListener('click', () => {
    document.body.classList.toggle("dark-mode");
    
    // Check the current state and save it to LocalStorage
    if (document.body.classList.contains("dark-mode")) {
        localStorage.setItem("themePref", "dark");
    } else {
        localStorage.setItem("themePref", "light");
    }
});

The one major limitation? Web Storage can only save Strings. If you want to save a complex JavaScript array or object (like a shopping cart), you must convert it to a string first using JSON.stringify(), and convert it back using JSON.parse() when you retrieve it.


🎯 The Final Piece of Vanilla JS

With the DOM, Events, Async/Await, and Web Storage under my belt, I have finally collected all the infinity stones of Vanilla JavaScript. I can now build a fully functional frontend. Tomorrow, the game changes. It is time to leave the raw code behind and step into the world of modern frameworks. Tomorrow, we install React.

Web Dev Day 15: Async/Await & Crypto Tracker

📅 Date: April 22, 2026

🧠 Mood: The FinTech Builder 📈

🔥 Topic: Web Dev Day 15: Async/Await & Crypto Tracker

🚆 Upgrading to the AC Local

Yesterday, I learned how to fetch data from the internet using JavaScript Promises. It worked, but writing endless .then() blocks felt exactly like navigating a crowded railway platform during Mumbai rush hour—messy, confusing, and prone to taking a wrong turn. In the developer world, deeply nested promises are notoriously called "Promise Hell."

Today, I learned the modern solution: Async/Await. If standard Promises are the regular crowded local train, Async/Await is the AC Local. It gets you to the exact same destination, but the journey is infinitely smoother, cleaner, and easier to read. It allows you to write asynchronous code that actually looks and behaves like normal, synchronous code.


✨ Syntactic Sugar: How it Works

Async/Await doesn't replace Promises; it just wraps them in a much nicer syntax.

1. The 'async' Keyword

When you put the word async in front of a function, you are telling the JavaScript engine: "Hey, this function is going to take some time. It will automatically return a Promise."

2. The 'await' Keyword

This is where the magic happens. You can only use await inside an async function. It literally tells the code to pause on that specific line until the data is fully fetched, without freezing the rest of the website. No more .then() chains!


💻 Project: Building a Live Crypto Tracker

I keep a close eye on the stock market and SIPs, so dealing with financial data is something I naturally gravitate towards. I decided to use the free CoinGecko API to fetch the live price of Bitcoin and display it. Notice how clean the try/catch block makes the error handling.

// 1. Declare the async function
async function fetchBitcoinPrice() {
    
    // 2. Use try/catch for clean error handling
    try {
        console.log("Fetching live data...");
        
        // 3. AWAIT the network request
        const response = await fetch('https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd');
        
        // 4. AWAIT the parsing of the JSON data
        const data = await response.json();
        
        // 5. Update the UI
        console.log(`Live Bitcoin Price: $${data.bitcoin.usd}`);
        document.getElementById('btc-display').innerText = `$${data.bitcoin.usd}`;
        
    } catch (error) {
        // This block only runs if the internet drops or the API fails
        console.error("Failed to fetch data:", error);
        document.getElementById('btc-display').innerText = "Error loading price.";
    }
}

// Trigger the function
fetchBitcoinPrice();

The code reads top-to-bottom, exactly like a story. Fetch the response -> Parse the JSON -> Update the UI. If anything breaks along the way, instantly jump to the Catch block. This is professional-grade JavaScript.


🎯 The Milestone Reached

With Async/Await, I now possess the ability to pull real-world data into my applications. The foundation of Front-End development is nearly complete. Tomorrow, we will look into LocalStorage—how to save user data directly in the browser so it doesn't disappear when they hit refresh!

Web Dev Day 14: JavaScript Promises & Fetch API

📅 Date: April 21, 2026

🧠 Mood: The Deal Maker 🤝

🔥 Topic: Web Dev Day 14: JavaScript Promises & Fetch API

🚦 Waiting for the Signal: A Promise Story

If you’ve ever been stuck on a train between Thane and Kandivali, you know the frustration of the "Signal." The train stops. You don't know when it will move again. You have a **Promise** from the railway that you will reach your destination, but right now, that promise is in a **Pending** state. You can either wait patiently (Success) or the train breaks down (Failure).

Web development works exactly the same way. When you ask a server for data—like your Instagram feed or a weather report—it takes time. You don't want your whole website to freeze while waiting. This is where **JavaScript Promises** come in. They are placeholders for a future value.


🤝 The Three States of a Promise

A Promise is an object representing the eventual completion (or failure) of an asynchronous operation. It can only be in one of three states:

1. Pending

The initial state. The operation hasn't finished yet. The train is still waiting for the signal.

2. Resolved (Fulfilled)

The operation completed successfully. You reached the station. We use the .then() block to handle this result.

3. Rejected

The operation failed. The train broke down. We use the .catch() block to handle the error gracefully without crashing the app.


💻 The Fetch API: Real World Data

The most common way we use Promises today is through the fetch() API. It allows us to go out to the internet, grab data, and bring it back to our UI. Here is how I fetched a random user's data today:

// Fetching data from a public API
fetch('https://jsonplaceholder.typicode.com/users/1')
    .then((response) => {
        // We first convert the raw response to JSON
        return response.json(); 
    })
    .then((data) => {
        // Now we can use the actual data
        console.log("User Name:", data.name);
        console.log("User Email:", data.email);
    })
    .catch((error) => {
        // If the internet is down or the URL is wrong
        console.error("Oops! Something went wrong:", error);
    });

Using .then() chains can get a bit messy (often called "Promise Hell"). In my next post, I will show you how to clean this up using the modern async/await syntax, which makes asynchronous code look like normal, synchronous code.


🎯 Today's Takeaway

The web is no longer static. It’s a network of interconnected APIs. Mastering Promises is the difference between a student project and a production-ready application. Stop waiting for the signal—start handling it.

Web Dev Day 13: Asynchronous JS (Timers & the Event Loop)

📅 Date: April 20, 2026

🧠 Mood: The Time Traveler ⏳

🔥 Topic: Web Dev Day 13: Asynchronous JS (Timers & the Event Loop)

🕒 Life in Parallel: Lessons from a Mumbai Local

If there is one thing that commuting from Thane to Kandivali teaches you, it's the art of "Asynchronous living." While I’m standing on the platform waiting for my train, I don't just stand still and do nothing else. I’m checking my emails, listening to a podcast, or reviewing my code notes on my phone. My life doesn't "freeze" just because one task (the train arriving) is taking its time.

JavaScript, by default, is a very "Synchronous" person. It executes code line by line. If a task takes 10 seconds to finish, the entire browser freezes until that task is done. You can't click buttons, you can't scroll—nothing. This is a nightmare for user experience. Today, I learned how JavaScript handles these "waiting periods" without breaking the flow.


⏳ The Magic of "Later": setTimeout and setInterval

To handle time-based tasks, JavaScript uses the Web APIs provided by the browser. These allow us to schedule code to run in the future.

1. setTimeout (The One-Shot)

Think of this as an alarm clock. You tell JavaScript: "Hey, take this function and run it exactly 3 seconds from now." The rest of your code keeps running immediately. When the 3 seconds are up, the browser pushes your function back into the execution line.

2. setInterval (The Heartbeat)

This is a repeating timer. It runs a piece of code every X milliseconds forever (or until you tell it to stop). This is perfect for things like digital clocks, countdown timers, or checking for new messages in a chat app.


💻 Practical: Non-Blocking Execution

I wrote a script to test if I could "order" my tasks. Notice how the code doesn't wait for the timer to finish before moving to the next line.

console.log("1. Starting my morning routine...");

// This task takes 2 seconds (simulating making coffee)
setTimeout(() => {
    console.log("2. Coffee is ready! ☕");
}, 2000);

console.log("3. Heading to the gym while coffee brews...");

/* OUTPUT:
1. Starting my morning routine...
3. Heading to the gym while coffee brews...
2. Coffee is ready! ☕ (Appears after 2 seconds)
*/

The fact that "3" prints before "2" blew my mind. It proves that JavaScript doesn't wait. It offloads the timer to the browser and keeps going. This is the foundation of the Event Loop—the secret mechanism that keeps the web fast.


🎯 The Next Milestone

Mastering timers is just the beginning of "Async" programming. While setTimeout is great, modern web development relies on Promises and Async/Await to fetch data from servers. Tomorrow, we take our first step into fetching real data from the internet!

Web Dev Day 12: Event Bubbling & Capturing

📅 Date: April 19, 2026

🧠 Mood: The Architect 🏛️

🔥 Topic: Web Dev Day 12: Event Bubbling & Capturing

📉 The Invisible Trap

Yesterday, I figured out how to make a button listen to my clicks using JavaScript events. It felt straightforward. You click the element, the function runs. But today, while trying to build a complex nested layout for a project, I ran into a bizarre bug that completely broke my logic.

I had a small "Delete" button placed inside a larger "Profile Card" div. I added a click event to the button to delete the user, and a click event to the card to open the profile details. But every time I clicked "Delete", both functions fired simultaneously. The user was deleted, but the profile page still tried to open, resulting in a massive console error.

That is when I learned the brutal reality of the DOM: Clicking a child element means you are simultaneously clicking every single parent element it sits inside. This phenomenon is known as Event Propagation, and it happens in two distinct phases: Capturing and Bubbling.


🌊 The Ripple Effect: Bubbling vs Capturing

Imagine throwing a stone into a pond. The ripple starts at the center and expands outward. JavaScript events work similarly across the DOM tree.

1. Event Bubbling (Bottom-Up)

This is the default behavior in modern browsers. When you click a button, the event triggers on the button first. Then, it "bubbles" up to the button's parent container, then to the grandparent container, all the way up to the <html> root. If any of those parents also have click listeners, they will execute in sequence.

2. Event Capturing (Top-Down)

Also known as the "Trickle Down" phase. This is the exact opposite. The browser starts at the very top of the document root and travels down through the parents until it finally hits the specific target button you clicked. You have to explicitly tell JavaScript to use this mode.


💻 The Fix: Stopping the Propagation

To fix my broken profile card, I didn't need to rewrite my HTML. I just needed to tell JavaScript to stop the ripple effect. We do this using a powerful built-in method called stopPropagation().

const profileCard = document.querySelector('.card');
const deleteBtn = document.querySelector('.delete-btn');

// Parent Event
profileCard.addEventListener('click', function() {
    console.log("Opening Profile Details...");
});

// Child Event
deleteBtn.addEventListener('click', function(event) {
    
    // 🔥 THE FIX: This stops the event from bubbling up to the card!
    event.stopPropagation(); 
    
    console.log("Deleting User Profile...");
});

By simply adding event.stopPropagation() to the child button, the event fires, does its job, and immediately dies. The parent card never even knows a click happened. Bug fixed.


🎯 The Golden Rule

Understanding the DOM tree is crucial. Whenever an event is firing twice or doing something unexpected, check your propagation path. Tomorrow, we move on to Asynchronous JavaScript. It's time to learn how the web handles time delays without freezing the browser.

Day 11: JavaScript Events & Form Handling

📅 Date: April 18, 2026

🧠 Mood: The Listener 👂

🔥 Topic: Web Dev Day 11: JavaScript Events & Form Handling

🚆 The Commuter's Code: Thane to Kandivali

Being an IT student in Mumbai is a grind that textbooks don't prepare you for. Most of my day is swallowed by the commute between Thane and my college in Kandivali. By the time I get home and hit the gym for my split, my brain is usually screaming for a break. But the brutal truth of the industry is that consistency beats intensity. You don't get hired for what you planned to do; you get hired for what you actually built.

I decided to pause my C++ DSA series temporarily to go "all-in" on Web Development. I want to see results that I can interact with. In the last post, we explored the DOM, but today we make it move. Today is about JavaScript Events—the bridge that turns a digital poster into a living, breathing application.


⚡ Interaction: Listening to the User

Events are essentially signals sent by the browser. When a user moves their mouse, types on a keyboard, or resizes a window, the browser broadcasts an event. As developers, our job is to set up "listeners" that wait for these signals and execute logic when they occur.

1. The addEventListener Method

In the past, developers used inline onclick attributes in HTML. This is a mess for scalability. The modern way is to use addEventListener() in your JavaScript file. It keeps your code separated and allows you to attach multiple logic blocks to a single element without them overriding each other.

2. Handling Forms with e.preventDefault()

The default behavior of an HTML form is to refresh the entire page upon submission. This is archaic. In modern MERN stack apps, we want to handle the data behind the scenes. We use event.preventDefault() to kill that refresh, allowing our JavaScript to capture the data and update the UI instantly.


💻 Practical: The Dynamic Input Logger

I built a small module that captures a user's name from an input field and displays a personalized welcome message without the page ever blinking. This is the foundation of every interactive feature, from login screens to live chat boxes.

// Selecting our target elements
const loginForm = document.querySelector('#auth-form');
const nameField = document.querySelector('#user-name');
const welcomeText = document.querySelector('#display-msg');

// Adding a listener for the 'submit' action
loginForm.addEventListener('submit', function(e) {
    
    // 🔥 CRITICAL: Stop the page from reloading
    e.preventDefault(); 
    
    const value = nameField.value;
    
    if(value.trim() === "") {
        console.warn("Input is empty!");
    } else {
        // Update the DOM dynamically
        welcomeText.innerText = `Access Granted: Welcome, ${value}! 🚀`;
        nameField.value = ""; // Reset the input field
    }
});

🎯 The Takeaway

JavaScript events are the pulse of the web. Without them, you aren't building a web app; you're just building a brochure. Learning how to capture and manipulate user intent is the first real step toward becoming a Full-Stack developer. Next up: Event Propagation (Bubbling vs Capturing)—the most common interview trap.

[Web Dev] Day 10: The DOM (Making Websites Alive)

📅 Date: April 13, 2026

🧠 Mood: The Puppeteer 🎭

🔥 Topic: Web Dev Day 10: The DOM (Making Websites Alive)

📉 The Discipline Dip

I have a confession to make. There has been a complete radio silence on this blog for the past week. From April 6th to 12th, I didn't write a single line of code. No C++, no JavaScript, nothing.

Was I busy? Maybe a little. But the brutal truth is that I let my discipline slip. The daily exhaustion of commuting from Thane to college, trying to maintain a 5-day gym split, and then staring at a laptop screen late at night completely drained my mental battery. I hit a wall of laziness. But ignoring the problem doesn't write code. Today, I forced myself back into the chair, opened VS Code on my Vivobook, and decided to tackle one of the most powerful concepts in web development: The DOM.


🌐 What is the Document Object Model (DOM)?

Up until now, JavaScript felt like a calculator. It could do math in the console, but it wasn't interacting with my beautifully styled HTML and CSS. The DOM is the bridge between them.

When your browser loads an HTML file, it converts every single tag (like <h1>, <p>, <button>) into an "Object" that JavaScript can read and manipulate. It creates a massive family tree of your website. If HTML is the puppet, the DOM gives JavaScript the strings to control it.

1. Grabbing the Elements

Before you can change a button, JavaScript needs to "grab" it from the screen. We do this using incredibly useful built-in methods like document.getElementById() or the more modern document.querySelector(). Once you hold the element in a JS variable, you have total power over it.

2. The Event Listener (Listening for actions)

Websites wait for you to do things. They wait for a click, a scroll, or a keyboard press. In JS, we attach an addEventListener to an element. It literally sits there in the background, listening. When the user clicks, it triggers a custom function to run instantly.


💻 Building a "Dark Mode" Toggle

To prove I actually learned this, I built a miniature Dark Mode toggle button. Just a few lines of JavaScript completely alter the CSS of the entire page without reloading it.

// 1. Grab the button and the body from the HTML
const themeBtn = document.getElementById("theme-toggle-btn");
const pageBody = document.body;

// 2. Add an Event Listener for a 'click'
themeBtn.addEventListener("click", function() {
    
    // 3. The Logic: Toggle a CSS class that contains dark mode styles
    pageBody.classList.toggle("dark-theme");
    
    // 4. Change the text of the button dynamically
    if (pageBody.classList.contains("dark-theme")) {
        themeBtn.innerText = "Switch to Light Mode ☀️";
    } else {
        themeBtn.innerText = "Switch to Dark Mode 🌙";
    }
});

The moment I clicked the button and saw the entire background color flip instantly, everything clicked in my head. This is how modern web apps like Twitter and YouTube handle their interfaces. No page reloads, just pure JavaScript manipulating the DOM.


🎯 What's Next?

The break is officially over. With DOM manipulation under my belt, I can finally start building interactive projects. Tomorrow, I will be combining HTML forms with JavaScript to capture user input dynamically. The MERN stack journey is finally getting real!

[Web Dev] Day 9: JavaScript (The Brain of the Web)

📅 Date: April 3, 2026

🧠 Mood: The Logic Builder 🧩

🔥 Topic: Web Dev Day 9: JavaScript (The Brain of the Web)

☕ The Biggest Rookie Mistake: Java vs JavaScript

My engineering exams are finally over, and it is time to get back to the daily grind. Up until now, I had only dealt with HTML (the skeleton) and CSS (the skin). But to make a website actually do something, you need to give it a brain. Today, I started learning that brain.

But before writing a single line of code, I made the most classic, embarrassing rookie mistake. I told my developer friend that I was "starting Java today for web development." He immediately corrected me with a brutal analogy: "Java and JavaScript are as similar as Car and Carpet."

They share a name for historical marketing reasons, but they are completely different languages. Java is a compiled, object-oriented backend heavy-lifter. JavaScript (JS) is the scripting language of the web. It is what makes your browser interactive. It handles button clicks, form submissions, and data fetching.


🧠 Entering the World of Logic

Coming from a C++ Data Structures background, stepping into JavaScript feels both incredibly familiar and wildly chaotic. C++ is strict; it yells at you if you forget a semicolon or use the wrong data type. JavaScript, on the other hand, is dangerously forgiving.

1. The Developer Console

The first thing I learned wasn't a complex algorithm; it was how to talk to the browser. By right-clicking any webpage and hitting "Inspect," you open the Developer Tools. The "Console" tab is where JS lives. It is our testing ground to print messages and debug code using the legendary command: console.log().

2. The Death of 'var'

In older tutorials, people used the var keyword to declare variables. I quickly learned that modern JS development strictly avoids it because it causes horrible bugs with memory scoping. Today, we only use let (for values that will change) and const (for values that stay exactly the same).


💻 First Lines of Code

To link JS to an HTML file, we use the <script> tag, usually placed right before the closing </body> tag so it doesn't block the website from loading its visual elements first. Here is my first script:

// This prints a message directly to the browser's developer console
console.log("Hello Web! The brain is now online.");

// Using 'const' because my name isn't going to change
const developerName = "Sahil";

// Using 'let' because my code experience level will increase!
let currentLevel = "Beginner";

console.log(developerName + " is currently a " + currentLevel);

It’s simple, but seeing that text appear in the browser console felt like unlocking a superpower. I am no longer just drawing boxes on a screen; I am manipulating data.


🎯 What's Next?

Syntax is just the beginning. Tomorrow, I will dive into JavaScript Functions and DOM Manipulation—the actual magic that allows us to click a button and change the webpage dynamically without refreshing!

[Web Dev] Day 8: CSS Transitions (Bringing UI to Life)

📅 Date: March 6, 2026

🧠 Mood: The Animator 🎬

🔥 Topic: Web Dev Day 8: CSS Transitions (Bringing UI to Life)

💀 The "Dead" Website Problem

Yesterday, I successfully built a responsive layout for a YouTube Video Grid. Structurally, it was perfect. It had rows, columns, and an organized navigation bar. But when I actually started using it and clicking around, something felt terribly off. The website felt rigid. It felt... dead.

When I hovered my mouse over a video thumbnail, the background color changed, but it happened instantly, in zero milliseconds. It was a harsh, aggressive visual snap that hurt the eyes. I realized that modern websites like Apple or Spotify don't do this. When you interact with their buttons, the changes happen smoothly. They glide. They feel natural.

That is when I discovered the secret sauce of modern UI/UX design: CSS Transitions. It is the bridge between a clunky amateur website and a premium, professional web application.


⏱️ Controlling Time with CSS

In plain HTML/CSS, state changes (like hovering over a button) happen instantly. CSS Transitions allow you to slow down that change over a specified duration of time. Instead of instantly snapping from "Blue" to "Red", you can tell the browser to slowly blend the colors over 0.5 seconds.

1. The Syntax Breakdown

To make a transition work, you need to define three main things on the original element:

  • Property: What are you animating? (e.g., background-color, transform, or all).
  • Duration: How long should it take? (e.g., 0.3s for 300 milliseconds).
  • Timing Function: How should the speed behave? (e.g., ease-in-out makes it start slow, speed up in the middle, and slow down at the end).

2. The Power of "Transform"

While transitioning colors is cool, the real magic happens when you combine transitions with the transform property. You can scale (zoom in), translate (move X/Y), or rotate elements. This is exactly how YouTube makes their video thumbnails slightly "pop out" when you hover your cursor over them.


💻 The 2-Line Magic Code

To fix my rigid YouTube grid, I didn't need a complex JavaScript animation library. I literally just added two lines of CSS to my video cards.

/* 1. The Default State (Add the transition here) */
.video-card {
    background-color: #121212;
    transform: scale(1); /* Normal size */
    
    /* The Magic Line: Animate all changes over 0.3 seconds smoothly */
    transition: all 0.3s ease; 
}

/* 2. The Hover State (What it should become) */
.video-card:hover {
    background-color: #202020; /* Slightly lighter background */
    transform: scale(1.05); /* Zoom in by 5% */
    border-radius: 12px; /* Smooth out the corners */
}

By simply adding transition: all 0.3s ease; to the parent element, the browser automatically calculates the intermediate frames. Now, when I hover over my video cards, they gently float up towards the screen, giving immediate, satisfying feedback to the user.


🎯 What's Next?

With layout and transitions down, my frontend skills are finally looking solid. But tomorrow is the weekend, which means taking a break from Web Development and returning to the brutal world of Data Structures and Algorithms. Get ready for the Divide and Conquer king: Merge Sort.

[Web Dev] Day 7: YouTube Grid Project

📅 Date: March 5, 2026

🧠 Mood: The Builder 🛠️

🔥 Topic: Web Dev Day 7: Building a YouTube Video Grid Clone

🧩 Putting the Puzzle Together

For the past week, I have been learning layout technologies in isolation. I learned Flexbox to align items in a single row. I learned CSS Grid to build two-dimensional matrices. And I learned Media Queries to prevent my designs from looking like a broken mess on mobile phones.

But theory is useless if you can't build anything with it. Today, I decided to test myself. The goal was simple but intimidating: Recreate the YouTube homepage layout from scratch using only HTML and CSS. No external frameworks like Bootstrap or Tailwind. Just raw code.


📸 The Final Result

After a few hours of debugging and tweaking pixels, here is what I managed to build.

SahilTube


🏗️ The Architecture Behind the Code

Breaking down a complex UI like YouTube requires you to think in boxes. I divided the entire project into two main components: The Navbar and the Video Grid.

1. The Navbar (Flexbox Territory)

The top navigation bar has three main sections: The Logo (left), the Search Bar (center), and the User Profile (right). This is the perfect use case for Flexbox. By setting the navbar container to display: flex; and using justify-content: space-between;, the browser automatically pushed the logo to the far left and the profile to the far right, leaving the search bar perfectly centered.

2. The Video Cards (CSS Grid Territory)

For the actual videos, I wrapped all the individual video cards inside a main <main class="video-grid"> container. Using CSS Grid, I was able to define exactly how many columns I wanted. But more importantly, I used Media Queries to make it fully responsive.

On a mobile phone, the CSS forces a 1-column layout. On a tablet, it switches to 2 columns. And on a wide desktop monitor, it gracefully expands to 4 columns (as seen in my screenshot above).


🎯 What I Learned

Building this project gave me an immense confidence boost. It proved that I finally understand how structure and layout work on the modern web. Now that I have mastered the "skeleton" (HTML) and the "skin" (CSS), it is almost time to dive into the "brain"—JavaScript.

[Web Dev] Day 6: Surviving the Mobile Screen

📅 Date: March 4, 2026

🧠 Mood: The Shape-Shifter 📱

🔥 Topic: Web Dev Day 6: Surviving the Mobile Screen (Media Queries)

📱 The Brutal Reality Check

Yesterday, I felt like an absolute genius. I had successfully used CSS Grid to create a flawless, symmetrical 3-column layout on my laptop. It looked professional, clean, and perfectly aligned. I deployed the code, shut my laptop, and went to sleep.

The reality check hit me the next morning. While commuting on the train to my college in Kandivali, I decided to open the live link on my smartphone just to admire my work. What I saw was a complete disaster.

The 3-column grid that looked so beautiful on a 15-inch monitor was now violently squished onto a 6-inch mobile screen. The images were unrecognizable, the text was overflowing, and the layout was completely broken. That is when I learned the hardest lesson of modern web development: Building for desktop is only half the battle. If your site doesn't work on mobile, it doesn't work at all.


🛠️ Enter CSS Media Queries

The solution to this nightmare is something called Media Queries. It acts as an "if-else" statement for your CSS. It literally asks the user's device: "Hey, how wide is your screen?"

Depending on the answer, Media Queries allow you to completely swap out your CSS rules. If the screen is wide (like a PC), show the 3-column grid. If the screen is narrow (like a phone), destroy the grid and stack everything vertically in a single column.

1. The Concept of Breakpoints

Breakpoints are specific pixel widths where your design "breaks" or starts looking bad. A common breakpoint for tablets is 768px, and for mobile phones, it is usually around 480px or smaller. As a developer, you write custom CSS that only triggers when the screen hits these specific breakpoints.

2. The Mobile-First Mindset

Instead of building a massive desktop site and then trying to shrink it down (which causes a lot of bugs), modern developers write the mobile code first. They use min-width media queries to add complexity only as the screen gets larger. It's much easier to scale up than to compress down.


💻 The Rescue Code

To fix my broken gallery, I didn't have to rewrite my entire HTML file. I just went into my CSS file and added this specific rule at the very bottom.

/* Default for mobile: 1 column */
.gallery-container {
    display: grid;
    grid-template-columns: 1fr;
    gap: 15px;
}

/* If the screen is wider than 768px (Tablets/PCs), switch to 3 columns */
@media (min-width: 768px) {
    .gallery-container {
        grid-template-columns: 1fr 1fr 1fr;
    }
}

Just like that, my site became "Responsive". On my phone, it showed a neat, scrollable single column of images. On my laptop, it expanded back into the 3-column grid.


🎯 What's Next?

I now have the three Infinity Stones of layout design: Flexbox, CSS Grid, and Media Queries. Tomorrow is the big day. I am going to combine all three of these technologies to build a fully responsive clone of the YouTube Video Grid. Stay tuned!

[Web Dev] Day 5: HTML Code (CSS Grid)

📅 Date: March 3, 2026

🧠 Mood: The Architect 🏗️

🔥 Topic: Web Dev Day 5: CSS Grid (The 2D Matrix)

🚧 Where Flexbox Fails

Yesterday, I was praising CSS Flexbox like it was the ultimate solution to all layout problems. And for a moment, I truly believed it was. But today, I hit a massive roadblock while trying to build a simple photo gallery layout.

I wanted a layout with exactly three columns of images. If I added a fourth image, I wanted it to perfectly snap into the next row directly beneath the first image. I tried doing this with Flexbox using flex-wrap, but the math kept getting messy. The items would stretch awkwardly, and the alignment wasn't perfectly symmetrical.

That is when I realized the brutal truth: Flexbox is one-dimensional. It is designed to lay things out in a single row OR a single column. It doesn't care about the relationship between items in different rows. To build a true matrix—a proper layout with perfectly aligned rows and columns simultaneously—you need CSS Grid.


📐 Thinking in Rows and Columns

If Flexbox is like placing items on a single shelf, CSS Grid is like building an Excel spreadsheet. You explicitly define how many columns you want and how wide they should be.

When I first looked at CSS Grid syntax, it looked incredibly intimidating. Words like grid-template-columns and fr units (fractions) made no sense to my brain, which was just getting used to pixels and percentages. But once you write it out, it becomes remarkably intuitive.

1. The Magical 'fr' Unit

Instead of calculating percentages (like 33.33% for three columns), Grid introduces the fractional unit (fr). If you want three equal columns, you simply tell the browser to give 1 fraction of the available space to each column. The browser handles all the complex math for you.

2. The Grid Gap

In the past, adding space between boxes meant messing around with margins and accidentally breaking the layout because the total width exceeded 100%. Grid has a built-in gap property. You just type gap: 20px; and it perfectly places 20 pixels of empty space between all your rows and columns, without pushing your items outside the container.


💻 The 3-Column Code Snippet

Here is the exact code I used to finally solve my photo gallery problem. Notice how clean and short the CSS is compared to older techniques.

.gallery-container {
    display: grid; /* Enables CSS Grid */
    
    /* Creates 3 columns of exactly equal width */
    grid-template-columns: 1fr 1fr 1fr; 
    
    /* Adds perfect 15px spacing between all items */
    gap: 15px; 
}

The moment I applied this class to my parent container, all my child divs instantly snapped into a perfect, uniform 3x3 grid. No messy margin calculations, no floating elements. Just pure geometric perfection.


🎯 What's Next?

Flexbox is for aligning things in a single line. Grid is for building the overall page structure. Tomorrow, I will dive into Media Queries to learn how to make this grid change shape when viewed on a small mobile phone versus a large desktop monitor.

[Web Dev] Day 4: HTML Code (CSS Flexbox)

📅 Date: March 2, 2026

🧠 Mood: The Layout Master 📐

🔥 Topic: Web Dev Day 4: The Magic of CSS Flexbox

🤯 The Nightmare of "Centering a Div"

If you look back at my Day 3 post where I built a Signup and Login page, you might think it was a smooth process. It absolutely was not. I spent an embarrassing amount of time just trying to put that login box in the dead center of the screen.

I tried using margins, padding, and absolute positioning. It looked fine on my laptop, but the moment I resized the browser window, the whole layout broke and looked like a mess. Historically, developers used horrible hacks like "floats" and "HTML tables" to align things. But today, I learned the modern solution: CSS Flexible Box Layout (Flexbox).

Flexbox is quite literally a lifesaver. It is a one-dimensional layout model that gives you absolute control over aligning items in a row or a column, distributing space dynamically even when the screen size changes.


📦 The Parent and The Children

The most important concept to understand about Flexbox is the relationship between the container and its items. You don't apply Flexbox to the item you want to move; you apply it to the Parent Container that holds the items.

By simply adding display: flex; to a parent div, all the child elements instantly become "flex items". By default, they will align themselves in a horizontal row. From there, you get access to two magical properties that dictate exactly where those children go:

1. justify-content (The X-Axis)

This property controls how the space is distributed along the main axis (usually horizontally). My favorite values are:

  • center: Pushes everything to the middle.
  • space-between: Pushes the first item to the far left, the last to the far right, and spreads the rest evenly. (Perfect for Navbars!).
  • space-around: Gives every item equal space around it.

2. align-items (The Y-Axis)

This controls the cross-axis (usually vertically). If your container is 500px tall, and you want your text exactly in the vertical middle, you simply use:

  • center: Vertically centers the items.
  • flex-start: Aligns them to the top.
  • flex-end: Aligns them to the bottom.

💻 The "Center Anything" Cheat Code

After struggling for hours previously, I realized that centering a div is now just three lines of CSS. If you ever need to put a box directly in the middle of the screen, just wrap it in a container and apply this CSS to the container:

.parent-container {
    height: 100vh; /* Takes full height of the viewport */
    display: flex; /* Enables Flexbox */
    justify-content: center; /* Centers horizontally */
    align-items: center; /* Centers vertically */
}

It feels almost illegal how easy this is compared to the old methods. Tomorrow, I will be looking into CSS Grid, which is meant for two-dimensional layouts, and then we will combine both to build a complete website layout.


🎯 Today's Takeaway

Don't fight the layout. Use Flexbox. It drastically reduces the amount of CSS you have to write and ensures your design doesn't break on different screen sizes. Next up: The CSS Grid system!