Make your own URL shortener in JavaScript

Make your own URL shortener in JavaScript


What is a URL Shortener?

A URL shortener is a tool that converts Long URLs into shorter, more manageable links. Once the URL has been shortened, it redirects users to the original URL. 

Short URLs are easier to share on social media, emails, or any other digital platform. Additionally, many URL shorteners offer advanced features such as tracking and analytics that can be useful in providing insights into user engagement.

In this tutorial, we will cover how to create your very own URL shortener tool using JavaScript!

By the end of this tutorial, we will have something like this:

Let’s get started!

Create UI with HTML and CSS

We will be using HTML and CSS to build a simple user interface, featuring the following elements:

  • A form element with a and a button for submission. 
  • A element to display the results and a tag to copy the shortened URL.
  • A   element for displaying any error messages
  • A   element to display a copied message when the URL is copied.

Add this code in the body of the HTML file.

1

class="container">

2
    URL Shortener
3
    
4
         type="url" id="url" placeholder="Enter your long URL" required>
5
        
6
    
7
    

id="result">

8
        Shortened URL:  target="_blank" id="shortened-url">
9
             id="icon" class="fa-solid fa-copy">
10
        
11
    
12
    

id="copy">Copied!

13
    

id="error">

14

Styling with CSS

Let’s rifle through some styles to get things looking the way we want.

To style the page, let’s start by setting the body to use display: flex; this will ensure everything is centered horizontally and vertically.

We’ll also add a background color.

1
body {
2
    display: flex;
3
    justify-content: center;
4
    align-items: center;
5
    height: 100vh;
6
    background-color: #f1f1f1;
7
    font-family: Arial, sans-serif;
8
}

Now let’s add these styles to the container element.

1
.container {
2
    width: 400px;
3
    background-color: #fff;
4
    border-radius: 5px;
5
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
6
    padding: 20px;
7
    text-align: center;
8
}

To ensure the elements in the form ( and



Source link