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

An Important Ingredient: Friends

This is going to be a very short and simple blog , just trying to tell you all about an important Ingredient to achieve anything in your life , not just necessarily for studies alone: A Good Friend Circle:-) According to my opinion....you know what?? YOU SHOW ME YOUR FRIENDS, I WILL TELL YOU ABOUT YOUR CHARACTER Listen , this is also a crucial point in deciding your success rate, specifically if you are a person with low self-esteem and not able to keep your-self self-motivated most of the times.                ----------[ Image by  Joseph Redfield Nino  from  Pixabay  ] --------- Always ,if possible to maintain a balance in the friend circle you make. And if not possible, you must at-least try to interact with people and friends who are of your own caliber and also with people of bit higher intellectual skills . It can help you, remain on the right track and also of-course ,each of you, can help sort out others problems( ...

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...