Skip to main content

Creating a URL shortener i

 


Creating a URL shortener is an excellent project to enhance your web development skills. In this comprehensive guide, we'll build a URL shortener using HTML, CSS, and JavaScript, ensuring a user-friendly interface and efficient functionality.

Table of Contents:

  1. Introduction
  2. Project Setup
  3. Building the Frontend
    • HTML Structure
    • CSS Styling
  4. Implementing the Backend
    • JavaScript Logic
    • URL Storage Mechanism
  5. Testing the Application
  6. Deploying the Application
  7. Conclusion

1. Introduction

A URL shortener transforms long URLs into concise, shareable links. This is particularly useful for platforms with character limits or for simplifying complex URLs. Our goal is to create a web application that allows users to input a long URL and receive a shortened version that redirects to the original link.

2. Project Setup

Begin by setting up your project directory and necessary files:

  • Project Structure:

    url-shortener/

    ├── index.html

    ├── styles.css

    └── script.js

  • Tools Needed:

    • A code editor (e.g., Visual Studio Code)
    • A web browser for testing

3. Building the Frontend

HTML Structure

Create an index.html file with the following structure:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>URL Shortener</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="container"> <h1>URL Shortener</h1> <form id="url-form"> <input type="url" id="long-url" placeholder="Enter the long URL" required> <button type="submit">Shorten URL</button> </form> <div id="result" class="hidden"> <p>Shortened URL:</p> <a id="short-url" href="#" target="_blank"></a> </div> </div> <script src="script.js"></script> </body> </html>

This structure includes a form for user input and a section to display the shortened URL.

CSS Styling

In styles.css, add the following styles to enhance the appearance:

body { font-family: Arial, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background-color: #f4f4f4; } .container { text-align: center; background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); } input[type="url"] { width: 80%; padding: 10px; margin-bottom: 10px; border: 1px solid #ccc; border-radius: 4px; } button { padding: 10px 20px; background-color: #007bff; color: #fff; border: none; border-radius: 4px; cursor: pointer; } button:hover { background-color: #0056b3; } .hidden { display: none; }

These styles create a clean and responsive interface for the URL shortener.

4. Implementing the Backend

JavaScript Logic

In script.js, implement the following logic:

document.getElementById('url-form').addEventListener('submit', function(event) { event.preventDefault(); const longUrl = document.getElementById('long-url').value; const shortCode = generateShortCode(); localStorage.setItem(shortCode, longUrl); displayShortUrl(shortCode); }); function generateShortCode() { return Math.random().toString(36).substring(2, 8); } function displayShortUrl(shortCode) { const shortUrl = `${window.location.origin}/#${shortCode}`; const resultDiv = document.getElementById('result'); const shortUrlLink = document.getElementById('short-url'); shortUrlLink.href = shortUrl; shortUrlLink.textContent = shortUrl; resultDiv.classList.remove('hidden'); }

This script handles form submission, generates a unique short code, stores the mapping in localStorage, and displays the shortened URL to the user.

URL Storage Mechanism

To handle redirection when a shortened URL is accessed, add the following code to script.js:

window.addEventListener('load', function() { const shortCode = window.location.hash.substring(1); if (shortCode) { const longUrl = localStorage.getItem(shortCode); if (longUrl) { window.location.href = longUrl; } else { alert('Invalid short URL'); } } });

This code checks if there's a hash in the URL (indicating a short code) and redirects to the corresponding long URL if it exists.

5. Testing the Application

To test the URL shortener:

  1. Open index.html in a web browser.
  2. Enter a long URL in the input field and click "Shorten URL."
  3. A shortened URL will be displayed.
  4. Copy and paste the shortened URL into the browser's address bar to verify redirection.

6. Deploying the Application

To make your URL shortener accessible online:

  1. Host the files on a web server or a platform like GitHub Pages.
  2. Ensure that the domain or URL where the application is hosted is consistent, as the shortened URLs depend on the base URL.

7. Conclusion

You've successfully built a simple URL shortener using HTML, CSS, and JavaScript. This project demonstrates how to handle user input, store data locally, and manage URL redirection. For a more robust solution, consider implementing a backend with a database to handle URL mappings and enhance security.

Comments

Popular posts from this blog

From Message Queues to Distributed Streams: A Comprehensive Introduction to Apache Kafka (Part 3)

In Part 1 and Part 2, we covered the basics of Kafka, its core concepts, and optimization techniques. We learned how to scale Kafka, secure it, govern data formats, monitor its health, and integrate with other systems. Now, in this final installment, we’re going to push deeper into advanced scenarios and look at how you can implement practical, production-ready solutions—especially with Java, the language of Kafka’s native client library. We’ll explore cross-data center replication, multi-cloud strategies, architectural patterns, advanced security, and more. We’ll highlight how to implement Kafka producers, consumers, and streaming logic in Java. By the end, you’ll have a solid understanding of complex Kafka deployments and the technical know-how to bring these ideas to life in code. Advanced Deployment Scenarios: Multi-Data Center and Hybrid Cloud As organizations grow, they may need Kafka clusters spanning multiple data centers or cloud regions. This can ensure higher availabilit...

From Message Queues to Distributed Streams: A Comprehensive Introduction to Apache Kafka (Part 2)

In the first part, we explored Kafka’s core concepts—topics, partitions, offsets—and discovered how it evolved from a LinkedIn project to a globally adored distributed streaming platform. We saw how Kafka transforms the idea of a distributed log into a powerful backbone for modern data infrastructures and event-driven systems. Now, in Part 2, we’ll step deeper into the world of Kafka. We’ll talk about how to optimize your Kafka setup, tune producers and consumers for maximum throughput, refine pub/sub patterns for scale, and use Kafka’s ecosystem tools to build robust pipelines. We’ll also introduce strategies to handle complex operational challenges like cluster sizing, managing topic growth, ensuring data quality, and monitoring system health. Get ready for a hands-on journey filled with insights, best practices, and practical tips. We’ll keep the paragraphs shorter, crisper, and more visually engaging. Let’s dive in! Scaling Kafka: Building a Data Highway Rather Than a Country ...

From Message Queues to Distributed Streams: A Comprehensive Introduction to Apache Kafka (Part 1)

In today’s data-driven world, the ability to effectively process, store, and analyze massive volumes of data in real-time is no longer a luxury reserved for a handful of tech giants; it’s a core requirement for businesses of all sizes and across diverse industries. Whether it’s handling clickstream data from millions of users, ingesting event logs from thousands of servers, or tracking IoT telemetry data from smart sensors deployed worldwide, the modern enterprise faces a formidable challenge: how to build reliable, scalable, and low-latency systems that can continuously move and transform data streams. Standing at the forefront of this revolution is Apache Kafka, an open-source distributed event streaming platform that has fundamentally redefined how organizations think about messaging, event processing, and data integration. Kafka’s rise to popularity is no accident. Originally developed at LinkedIn and later open-sourced in 2011, Kafka was conceived to address some of the toughest...