Building a Simple URL Shortener With HTML and Javascript

Building a Simple URL Shortener With HTML and Javascript

In this article, you''l learn how to build a simple URL shortener with HTML and Javascript

In this article, you''l learn how to build a simple URL shortener with HTML and Javascript

URL Shortener, you might have used one of them in your life such as bit.lygoo.gl and much more. They are useful for shortening long URLs so that you can easily share them with your friends, family or co-workers.

You might be wondering how these things work? To understand how these things work, we need to take a closer look at an url shortener so we’ll be building a simple url shortener. With That Task, we’ll be learning some new things as well as understand how URL Shortener works.

Today, we'll be building a simple url shortener which does not need a database system to host yourself, instead, we'll use jsonstore.io, I'll be assuming that you already know some basic HTML & Javascript.

So without further talking, Let's Start Building. . .

Start with HTML Part :

we'll need only a text input box, a button, and a script tag to create our url shortener.

first create an HTML file called index.html, as there is only a need of two elements, a text input box, a button.

So Let's start adding our three main elements,

<html>
    <body>
        <input type="url" id="urlinput">
        <button onclick="shorturl()">Short The URL</button>
        <script src="main.js"></script>
    </body>
</html>

As I shown in the above code, I've created a simple HTML file. Inside body tags, there're only three elements an input, a button and a script.

the first element is input where we well type/paste our long url, I gave it an id name urlinput so it would be easy to access it inside javascript.

Next element is a button, when we click this button our long url will be shortened as it has onclickfunction which will be executed when we click the button, inside the shorturl() function there will be commands necessary to shorten the url.

At the end we have a script called main.js where all our main javascript codes will be in, above mentioned shorturl() function will be also there.

So, for now, our HTML part is complete. so let's start writing some javascript

Start writing some Javascript :

As we shown above, we'll need some javascript to create our url shortener.

Step 0: as I mentioned at first we'll be using jsonstore.io to store information about our long url, we will need a jsonstore.io endpoint url to store data, Visit jsonstore.io, you'll see something like below

Under the text This Is Your Endpoint you can see a text box with long url such as,

https://www.jsonstore.io/8ba4fd855086288421f770482e372ccb5a05d906269a34da5884f39eed0418a1

click the purple COPY button.

So Now, let's start writing some javascript . . .

create a javascript file called main.js and start following below steps

first, we must keep the copied link a variable

var endpoint = "https://www.jsonstore.io/8ba4fd855086288421f770482e372ccb5a05d906269a34da5884f39eed0418a1";

then we need to generate some random string so that we can create a link between the short url and the long url.

Assume, we have a random url abcd, our simple url shortener is hosted on https://shortner.com and we have shortened the url https://google.com with that random url, so whenever we go to https://shortner.com/#abcd we will be redirected to https://google.com
So, now well create a function called getrandom()

function getrandom(){
    var random_string = Math.random().toString(32).substring(2, 5) + Math.random().toString(32).substring(2, 5);
    return random_string()
}

Don't worry, I'll help you understand the above code,

first, we initiated a function called getrandom than we initialized a variable called random_string and gave it a value.

Math is a built-in javascript object which allows us to perform mathematical tasks on numbers. first we called the random function from Math , Math.random() returns a random number between 0 (inclusive), and 1 (exclusive)

Assume, we have a random url abcd, our simple url shortener is hosted on https://shortner.com and we have shortened the url https://google.com with that random url, so whenever we go to https://shortner.com/#abcd we will be redirected to https://google.com
Then we transform the returned number to a string using toString() and we gave it an argument of 32 so that we get a proper string not a binary, hexadecimal or octal,

Then we use substring(2,5) as well to slice the string and maintain the size of the string, then again we follow the same procedure to get another chunk of a random string and finally we add both chunks of the string using +

and don't forget to add a return statement returning our random string.

Assume, we have a random url abcd, our simple url shortener is hosted on https://shortner.com and we have shortened the url https://google.com with that random url, so whenever we go to https://shortner.com/#abcd we will be redirected to https://google.com

function getrandom() {
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for (var i = 0; i < 5; i++)
        text += possible.charAt(Math.floor(Math.random() * possible.length));
    return text;
}


Now Return to index.html and add JQuery because it will be easy to achieve our goals with ease if we use JQuery.

add at the end of body tag but before the main.js script tag

now again return to main.js

let's Create a Function called geturl which will take the value from the input box verify it and return the value

function geturl(){
    var url = document.getElementById("urlinput").value;
    var protocol_ok = url.startsWith("http://") || url.startsWith("https://") || url.startsWith("ftp://");
    if(!protocol_ok){
        newurl = "http://"+url;
        return newurl;
        }else{
            return url;
        }
}

in geturl function we first store the value of the input box in url variable. Then we check if url protocols are ok or not and if the protocol doesn't start with http:// , https:// or ftp:// we add http:// at the beginning of the url then return the url.

Now we will need another function to change the hash in the location bar, let's create

function genhash(){
    if (window.location.hash == ""){
        window.location.hash = getrandom();
    }
}

At first, we check if the hash location is empty if it's empty we than add a random hash to the location bar.

Assume, we have a random url abcd, our simple url shortener is hosted on https://shortner.com and we have shortened the url https://google.com with that random url, so whenever we go to https://shortner.com/#abcd we will be redirected to https://google.com
Next, we'll work on our main function shorturl() , so let's go...

function shorturl(){
    var longurl = geturl();
    genhash();
    send_request(longurl);
}

At first we store the long url in longurl variable then we add a random hash to the location bar so that we can use the url as the short url , then we call the send_request() with an argument longurl , in this function we send JSON request to jsonstore to store the long url with a link to short url , so now let's create the send_request() function.

function send_request(url) {
    this.url = url;
    $.ajax({
        'url': endpoint + "/" + window.location.hash.substr(1),
        'type': 'POST',
        'data': JSON.stringify(this.url),
        'dataType': 'json',
        'contentType': 'application/json; charset=utf-8'
})
}

Here we use JQuery to send JSON request, we send the request to endpoint+"/" + our random string hash from the location bar

as an example,

https://www.jsonstore.io/8ba4fd855086288421f770482e372ccb5a05d906269a34da5884f39eed0418a1/abcd

so whenever we will send a get request to the above-mentioned url we'll get the long url as data

Important : add the send_request() function before the shorturl() function , otherwise it will not work

Assume, we have a random url abcd, our simple url shortener is hosted on https://shortner.com and we have shortened the url https://google.com with that random url, so whenever we go to https://shortner.com/#abcd we will be redirected to https://google.com> Assume, we have a random url abcd, our simple url shortener is hosted on https://shortner.com and we have shortened the url https://google.com with that random url, so whenever we go to https://shortner.com/#abcd we will be redirected to https://google.com
now we will the code to GET the long url linked to the short url entered in the address bar

var hashh = window.location.hash.substr(1)

if (window.location.hash != "") {
    $.getJSON(endpoint + "/" + hashh, function (data) {
        data = data["result"];

        if (data != null) {
            window.location.href = data;
        }

    });


then the above-mentioned code will be executed whenever we put the short url in the address bar (eg. https://shorturl.com/#abcd )

at first, we store the hash value from the url to the hashh variable.

Assume, we have a random url abcd, our simple url shortener is hosted on https://shortner.com and we have shortened the url https://google.com with that random url, so whenever we go to https://shortner.com/#abcd we will be redirected to https://google.com
then we check if the hash location is empty or not, if not empty we send a get request to the address, endpoint + hashh
Assume, we have a random url abcd, our simple url shortener is hosted on https://shortner.com and we have shortened the url https://google.com with that random url, so whenever we go to https://shortner.com/#abcd we will be redirected to https://google.com

https://www.jsonstore.io/8ba4fd855086288421f770482e372ccb5a05d906269a34da5884f39eed0418a1/abcd

and as usual, if everything is okay we will get the long url from the data which is a JSON array data, from that we extract the result with data["result"].

Assume, we have a random url abcd, our simple url shortener is hosted on https://shortner.com and we have shortened the url https://google.com with that random url, so whenever we go to https://shortner.com/#abcd we will be redirected to https://google.com
Our URL Shortener is Almost Complete! Copy-Paste a long url in the input box then click Short The URL button! Copy The Link from Address Bar, it's your short url!

Some Useful Tricks

We can add a function to automatically copy the short url when a user clicked the Short The URL button Using libraries like SimpleCopy, or ClipboardJS to copy the short url which is currently in the location bar.

if using SimpleCopy We can add simplecopy(window.location.href); at the end of shorturl() function copy the short url whenever use shortens a url

This Simple Url shortener relies on third-party libs such as jsonstore so it would not be a good idea to shorten some confidential long url with it.

You can host the Whole Project in Github/Gitlab pages and set up a simple CNAME, that's it your brand new personal url shortener is ready, you can use any static site hosting service to host your url shortener.

Learn HTML5 Canvas - DRAW - HTML & JavaScript

Learn HTML5 Canvas - DRAW - HTML & JavaScript

We go over the basics of the HTML5 Canvas element and use JavaScript to draw lines, circles, squares and rectangles to the DOMs Canvas. JavaScript combined with HTML5 Canvas can be used to draw elements anywhere you want inside of the HTML5 Canvas. We learn the basics in a simple how to video but in the next part we will look how to animate the HTML5 Canvas using JavaScript to change the X & Y coordinates of shapes we create. We will follow an Object Oriented Programming pattern.

Modal Tutorial - Using CSS, Html and JavaScript

Modal Tutorial - Using CSS, Html and JavaScript

In this tutorial, we will be creating a simple modal with CSS and JavaScript. In fact, we will be using the same code and Modal Tutorial - Using CSS and JavaScript. structure that the modal used here on Sabe uses as well for the feedback option at the end of this tutorial.

Introduction

Modal popups are used pretty frequently on the web. Some popular uses of them include driving newsletter signups, displaying notifications/alerts, and handling register and login forms.

Our modal will be generic which means you will be free to use it for whatever purpose you'd like. Here's what they will look like once finished:

The modal before opening.

The modal after opening.

You can view a live demo of the finished product before continuing on. Now, let's get started on building this!

HTML Markup

Let's start with the markup for the modal.

	
    <button class="trigger">Click here to trigger the modal!</button>
    <div class="modal">
        <div class="modal-content">
            <span class="close-button">&times;</span>
            <h1>Hello, I am a modal!</h1>
        </div>
    </div>
	

We have three different components here in the markup.

First we have a simple button which, when clicked on, triggers the modal to open. Then we have the modal's parent container which houses the modal. Finally, we have the content that will go inside the modal, plus a close button.

To keep things simple, the only actual content inside the modal is an h1 tag with some text.

CSS Styles

These are the styles we will apply to make our modal look nice and pretty.

	
    .modal {
        position: fixed;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        opacity: 0;
        visibility: hidden;
        transform: scale(1.1);
        transition: visibility 0s linear 0.25s, opacity 0.25s 0s, transform 0.25s;
    }
    .modal-content {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background-color: white;
        padding: 1rem 1.5rem;
        width: 24rem;
        border-radius: 0.5rem;
    }
    .close-button {
        float: right;
        width: 1.5rem;
        line-height: 1.5rem;
        text-align: center;
        cursor: pointer;
        border-radius: 0.25rem;
        background-color: lightgray;
    }
    .close-button:hover {
        background-color: darkgray;
    }
    .show-modal {
        opacity: 1;
        visibility: visible;
        transform: scale(1.0);
        transition: visibility 0s linear 0s, opacity 0.25s 0s, transform 0.25s;
    }
	

The styles here should be pretty simple, but here's a great class on CSS if you need a refresher.

Let's break down what we're doing.

	
    .modal {
        position: fixed;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        opacity: 0;
        visibility: hidden;
        transform: scale(1.1);
    }
	

The styles for the modal class makes it so that it creates a semi-transparent dark background color behind the modal when it is active. We stretch it to 100% width and height and set its visibility to hidden so that it doesn't appear.

	
    .modal-content {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background-color: white;
        padding: 1rem 1.5rem;
        width: 24rem;
        border-radius: 0.5rem;
    }
	

Then with the modal-content class, we position the actual modal in the center of the screen, with some visual goodies like a border-radius and some padding.

	
    .close-button {
        float: right;
        width: 1.5rem;
        line-height: 1.5rem;
        text-align: center;
        cursor: pointer;
        border-radius: 0.25rem;
        background-color: lightgray;
    }
    .close-button:hover {
        background-color: darkgray;
    }
	

To allow us to close the modal in an elegant way, we have a close button that is just a nicely styled X button at the top-right corner of the modal.

	
    .show-modal {
        opacity: 1;
        visibility: visible;
        transform: scale(1.0);
        transition: visibility 0s linear 0s, opacity 0.25s 0s, transform 0.25s;
    }
	

Finally, we have our class that handles styling the modal when it is opened.

All you need to do is give the modal the show-modal class to open it. Removing this class will reset it back to hidden. JavaScript will handle this toggling for us.

JavaScript Code

To make our modal popup actually work, we will be using a very tiny amount of pure, vanilla JavaScript.

	
    var modal = document.querySelector(".modal");
    var trigger = document.querySelector(".trigger");
    var closeButton = document.querySelector(".close-button");

    function toggleModal() {
        modal.classList.toggle("show-modal");
    }

    function windowOnClick(event) {
        if (event.target === modal) {
            toggleModal();
        }
    }

    trigger.addEventListener("click", toggleModal);
    closeButton.addEventListener("click", toggleModal);
    window.addEventListener("click", windowOnClick);
	

We set three click listeners here:

  • When the trigger is clicked, we want to show the modal.
  • When the close button is clicked, we want to hide the modal.
  • When the dark background is clicked, we want to also hide the modal.

Great! Now if we were to press the trigger or the close button, the modal should smoothly animate between the states. It's all about the pretty animations. 😍

Again, you can click here for a live demo of what we created, or use the editor below!

Further reading:

Javascript Objects Tutorial Example

Introduction To Promised-based Data Fetching In JavaScript

Beginners Guide to Tagged Template Literals in JavaScript

How to Jest Snapshot Test the Difference

Laravel 5.8 Tutorial - Datatables Dropdown Filter Server-side using Ajax

Top 8 VS Code Extensions Every Javascript Developer Must Know and Use

JavaScript Promises Tutorial with Examples

JavaScript Table Filter or Search | How to add Filter In HTML CSS Table

JavaScript Table Filter or Search | How to add Filter In HTML CSS Table

How we can add a search or filter option in an HTML Table using ... Solution: JavaScript Table Filter or Search, Add Filter In HTML CSS Table.

How we can add a search or filter option in an HTML Table using JavaScript? Solution: JavaScript Table Filter or Search, Add Filter In HTML CSS Table.

Previously I have shared a responsive table design, But how we can add a filter option in the table. Maybe you have seen on some websites, where you can search for a specific condition in the table. Like if ever you have visited any websites backend dashboard, then you probably know that we can be filtering out for any user by putting some conditions.

Today you will learn to create filter option for the HTML table using JavaScript. Using this program you can search for specific tables content by searching name, email, id, etc. This is a short & pure JavaScript program for table filter, you can use this on any kind of table on any place. You can use this on your next project, I know using jQuery we can create advanced filtering functions. But it is for showing how can we create the feature using pure JS.

So, Today I am sharing JavaScript Table Filter or Search for HTML Tables. Basically, This program is for Add FIlter In HTML & CSS Based Table. I have used Bootstrap for creating the table’s layout, & used CSS little bit for styling. In this table I have added some data, you add more according to your need. Or another option is to use the JS code & put it your own table.

If you are thinking now how this Filter Table actually is, Then see the preview given below.

Preview Of Add Filter In HTML CSS Tables

See this video preview to getting an idea of how this filter program looks like.


Now you can see this visually. If you like this, then get the source code of its.

You May Also Like:

  • JavaScript Portfolio Filter
  • Multi Step Form
  • Find Text & Highlight
  • Animated Newsletter Signup Form
JavaScript Table Filter or Search Source Code

Before sharing source code, let’s talk about this. As you know this is an HTML table, I have used Bootstrap & CSS to create the layout. This is a simple <td> and <tr> based table. In the filter fields, I have used HTML data-* (get info) attribute search & sorting them. In the CSS file, styled some elements like heading, table. As you can see in the preview the tables are colored in odd-even order, For creating that I used CSS :nth-of-type() property.

In the JavaScript section, I create a variable named var TableFilter and put all the functions inside it. In HTML we stored custom data using Data-* element, Now JS fetches it using .getAttribute method. Now javascript find the filtering text using a function called function _filter(row) If any data matches the input then its display that.

I know to explain the JS code in writing is taught, You will automatically understand after getting the codes. If you have some knowledge of JavaScript then you will definitely understand.

For creating this program you have to create 3 files. First for HTML, second for CSS, & third for JavaScript. Follow the steps to creating this without any error.

index.html

Create an HTML file named ‘index.html‘ and put these codes given here below.

<!DOCTYPE html>
<!--Code By Webdevtrick ( https://webdevtrick.com )-->
<html lang="en" >
 
<head>
  <meta charset="UTF-8">
  <title>Light Javascript Table Filter</title>
  
  <link href="https://fonts.googleapis.com/css?family=Lato&display=swap" rel="stylesheet">
  <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
  <link href="style.css" rel="stylesheet">
  
  
</head>
 
<body>
 
  <section class="container">
 
	<h1>Table Filter JavaScript</h2>
 
	<input type="search" class="light-table-filter" data-table="table-info" placeholder="Filter/Search">
 
	<table class="table-info table">
		<thead>
		<tr>
		<th>Name</th>
		<th>Email</th>
		<th>Phone No</th>
		<th>ID</th>
		</tr>
		</thead>
		<tbody>
		<tr>
		<td>John Doe</td>
		<td>[email protected]</td>
		<td>0123456789</td>
		<td>01</td>
		</tr>
		<tr>
		<td>Alen Fox</td>
		<td>[email protected]</td>
		<td>0155456789</td>
		<td>02</td>
		</tr>
		<tr>
		<td>Rakesh Sharma</td>
		<td>[email protected]</td>
		<td>6754328901</td>
		<td>03</td>
		</tr>
		<tr>
		<td>Bunty Singh</td>
		<td>[email protected]</td>
		<td>5678241598</td>
		<td>04</td>
		</tr>
		<tr>
		<td>Sushant Rajput</td>
		<td>[email protected]</td>
		<td>675457801</td>
		<td>05</td>
		</tr>
		<tr>
		<td>Sunny Sharma</td>
		<td>[email protected]</td>
		<td>675123451</td>
		<td>06</td>
		</tr>
		<tr>
		<td>Saurav Gupta</td>
		<td>[email protected]</td>
		<td>61234801</td>
		<td>07</td>
		</tr>
		<tr>
		<td>Appu Khote</td>
		<td>[email protected]</td>
		<td>67894561</td>
		<td>08</td>
		</tr>
		<tr>
		<td>Sandeep Arya</td>
		<td>[email protected]</td>
		<td>741852963</td>
		<td>09</td>
		</tr>
		<tr>
		<td>Vijay Mehra</td>
		<td>[email protected]</td>
		<td>456851982</td>
		<td>10</td>
		</tr>
		</tbody>
	</table>
 
</section>
 
    <script  src="function.js"></script>
 
</body>
</html>

style.css

Now create a CSS file named ‘style.css‘ and put these codes.

/** Code By Webdevtrick ( https://webdevtrick.com ) **/
body {
    margin-top: 150px;
    font-family: 'Lato', sans-serif;
}
input {
    width: 200px;
    border-radius: 5px;
    text-align: center;
    border: 1px solid #212121;
    height: 40px;
}
table {
    margin-top: 30px;
}
tr:nth-of-type(even) {
    background: #ffd98b;
}
thead {
    background: #fbb016;
}

function.js

The final step, Create a JavaScript file named ‘function.js‘ and put the codes.

/* Code By Webdevtrick ( https://webdevtrick.com ) */
(function(document) {
	'use strict';
 
	var TableFilter = (function(Arr) {
 
		var _input;
 
		function _onInputEvent(e) {
		_input = e.target;
		var tables = document.getElementsByClassName(_input.getAttribute('data-table'));
		Arr.forEach.call(tables, function(table) {
		Arr.forEach.call(table.tBodies, function(tbody) {
		Arr.forEach.call(tbody.rows, _filter);
		});
		});
		}
 
		function _filter(row) {
		var text = row.textContent.toLowerCase(), val = _input.value.toLowerCase();
		row.style.display = text.indexOf(val) === -1 ? 'none' : 'table-row';
		}
 
		return {
		init: function() {
		var inputs = document.getElementsByClassName('light-table-filter');
		Arr.forEach.call(inputs, function(input) {
		input.oninput = _onInputEvent;
		});
		}
		};
	})(Array.prototype);
 
	document.addEventListener('readystatechange', function() {
		if (document.readyState === 'complete') {
		TableFilter.init();
		}
	});
 
})(document);

That’s It. Now you have successfully created JavaScript Table Filter or Search. In other words, Add Filter In HTML CSS Table. If you have any doubt or question comment down below.

Thanks For Visiting, Keep Visiting. If you liked this post, share it with all of your programming buddies!

This post was originally published here