This article provides the complete source code for a lightweight, entirely client-side URL Shortener tool. Designed with pure HTML, CSS, and JavaScript, this utility transforms long, cumbersome URLs into clean, shareable links. It's an ideal JavaScript project for developers, offering a practical tool that can be added to any website or portfolio without needing a complex backend or database.
The tool's core functionality relies on two powerful, free-to-use APIs. It utilizes the TinyURL API for reliable link shortening and instantly generates a scannable QR code for every shortened link by integrating the QuickChart API. This dual-feature approach ensures users get both a short link and a mobile-friendly QR code from a single action.
You can find the full, copy-paste-ready source code below, separated into clear HTML, CSS, and JS blocks for easy implementation. This guide provides everything needed to deploy this free URL shortener tool on your own site, offering a valuable, self-contained utility for you or your visitors.
The Source Code (Separated by HTML, CSS, & JS)
To make it easy to understand, we've broken the full source code into its three core components. The HTML builds the structure, the CSS makes it look good, and the JavaScript provides all the functionality.
1. The HTML (The Structure)
This is the skeleton of our tool. It's a single <div> with the class "container" that holds all the visible elements. You'll see the <input> field for the long URL, the "Shorten" and "New" buttons, and the <div> with the ID "result-box". This result box is hidden at first and will only appear once the JavaScript successfully creates a short link.
<div class="container">
<div class="title">URL Shortener</div>
<p class="sub">Paste a link to shorten it instantly</p> <input id="long-url" type="text" placeholder="https://example.com/your/link" /> <div class="actions">
<button class="btn primary" onclick="shortenURL()">Shorten</button>
<button class="btn" onclick="resetShortener()">New</button>
</div> <p id="error-msg"></p> <div id="result-box">
<div class="res-row">
<label>Short URL:</label>
<input id="short-url" readonly />
</div><div class="res-actions">
<button class="btn" onclick="copyShortURL()" id="copy-btn">Copy</button>
<a id="open-btn" class="btn" target="_blank">Open</a>
<button class="btn" onclick="shareShortURL()">Share</button>
</div>
<div class="qr-wrap">
<img id="qr-img" alt="QR Code" />
<br />
<button class="btn" onclick="downloadQR()">Download QR</button>
</div>
<div class="meta" id="meta-line"></div>
</div>
</div>
2. The CSS (The Style)
This CSS code is what gives the tool its modern and clean look. It styles the container with a soft gradient and shadow, makes the buttons and inputs look professional, and adds hover effects. Most importantly, it uses @media queries at the end to make the tool fully responsive, so it looks just as good on a mobile phone as it does on a desktop.
.container{background:linear-gradient(180deg,#ffffff,#f7f9ff);border:1px solid #e8ecff;border-radius:24px;box-shadow:0 10px 30px rgba(11,114,231,0.12);padding:22px 18px 20px}
.title{text-align:center;font-size:22px;font-weight:600}
.sub{text-align:center;color:#5b6b8a;margin-top:4px;font-size:13px}
input[type="text"]{width:100%;padding:14px;border:1px solid #d7def0;border-radius:14px;font-size:15px;background:#fff;outline:none}
input[type="text"]:focus{border-color:#0b72e7;box-shadow:0 0 0 3px rgba(11,114,231,0.15)}
.actions{display:flex;gap:10px;margin-top:12px}
.btn{padding:11px 14px;border-radius:12px;cursor:pointer;font-weight:600;border:1px solid #dfe6fb;background:#fff}
.btn.primary{background:#0b72e7;color:#fff;border:none}
.btn.primary:hover{background:#095bb5}
.btn:hover{transform:translateY(-1px);box-shadow:0 6px 14px rgba(11,114,231,0.12)}
#error-msg{color:#d14646;font-size:13px;margin-top:8px}
#result-box{margin-top:18px;padding:14px;border:1px solid #dfe6fb;border-radius:16px;background:#fff;display:none}
.res-row{display:grid;grid-template-columns:110px 1fr;gap:10px}
.res-actions{display:flex;gap:10px;margin-top:12px;flex-wrap:wrap}
.qr-wrap{margin-top:14px;text-align:center}
.qr-wrap img{width:140px;height:140px;border-radius:12px;border:1px solid #e6ecff}
.meta{margin-top:10px;color:#5b6b8a;font-size:12px}
@media (max-width:600px){.container{padding:16px;border-radius:18px}
.title{font-size:20px}
input[type="text"]{font-size:14px;padding:12px}
.res-row{grid-template-columns:1fr}
.res-row label{display:none}
.qr-wrap img{width:120px;height:120px}
}
@media (min-width:1000px){.container{width:600px}
.title{font-size:24px}
input[type="text"]{font-size:16px}
.qr-wrap img{width:160px;height:160px}
}
3. The JavaScript (The Brains)
This is where all the logic happens. The shortenURL() function is the star of the show. It's an async function, meaning it waits for the API call to finish. It grabs the user's input, validates it, and then uses the fetch() API to send it to TinyURL. When it gets a successful response, it updates the page, builds the QuickChart QR code URL, and makes the result box visible. We also have helper functions like copyShortURL() which uses the browser's navigator.clipboard API, and downloadQR() which cleverly uses an HTML canvas to create a downloadable image.
function normalizeUrl(url){ if(!url)return ""; url=url.trim(); if(/^https?:\/\//i.test(url))return url; return "https://"+url; } async function shortenURL(){ const input=document.getElementById("long-url").value; const url=normalizeUrl(input); const err=document.getElementById("error-msg"); const box=document.getElementById("result-box"); err.textContent=""; box.style.display="none"; try{ new URL(url); }catch{ err.textContent="Invalid URL. Example: https://google.com"; return; } try{ const res=await fetch( "https://tinyurl.com/api-create.php?url="+encodeURIComponent(url) ); if(!res.ok)throw new Error(); const shortUrl=(await res.text()).trim(); document.getElementById("short-url").value=shortUrl; document.getElementById("open-btn").href=shortUrl; document.getElementById("qr-img").src= "https://quickchart.io/qr?size=260&margin=2&text="+shortUrl; document.getElementById("meta-line").textContent="Original: "+url; box.style.display="block"; }catch{ err.textContent="Failed to shorten URL. Try again."; } } function resetShortener(){ document.getElementById("long-url").value=""; document.getElementById("short-url").value=""; document.getElementById("qr-img").src=""; document.getElementById("meta-line").textContent=""; document.getElementById("result-box").style.display="none"; document.getElementById("error-msg").textContent=""; } async function copyShortURL(){ const input=document.getElementById("short-url").value; const btn=document.getElementById("copy-btn"); try{ await navigator.clipboard.writeText(input); btn.textContent="Copied!"; }catch{ btn.textContent="Failed"; } setTimeout(()=>(btn.textContent="Copy"),1500); } function shareShortURL(){ const url=document.getElementById("short-url").value; if(navigator.share){ navigator.share({title:"Short URL",url}).catch(()=>{}); }else{ copyShortURL(); } } function downloadQR(){ const img=document.getElementById("qr-img"); if(!img.src)return; const canvas=document.createElement("canvas"); const ctx=canvas.getContext("2d"); const pic=new Image(); pic.crossOrigin="anonymous"; pic.onload=function(){ canvas.width=pic.width; canvas.height=pic.height; ctx.drawImage(pic,0,0); const a=document.createElement("a"); a.download="qr.png"; a.href=canvas.toDataURL(); a.click(); }; pic.src=img.src; }
How to Install the Tool
Getting this tool running on your website is incredibly simple. Because it's built purely with client-side code, you don't need any server setup or database. You have two main options:
- Create a Standalone HTML File: This is the fastest way to see it work.
- Create a new file named
shortener.html. - Copy and paste the entire code from the original post (or combine the three blocks above) into this file. Make sure the CSS is inside
<style>tags in the<head>and the JavaScript is inside<script>tags before the closing</body>. - Save the file and open it in any web browser. It will work instantly.
- Create a new file named
- Embed in Your Existing Website: This is the best way to add it as a feature for your users.
- HTML: Copy the HTML block (the
<div class="container">...</div>) and paste it into the<body>of the page where you want it to appear. - CSS: Copy the CSS block and add it to your website's main stylesheet (e.g.,
style.css). - JavaScript: Copy the JavaScript block and add it to your website's main
.jsfile, or place it in a<script>tag at the bottom of your HTML body.
- HTML: Copy the HTML block (the
Once embedded, you can test it by pasting a long URL, generating the short link, and testing the copy and QR features.
Customization Tips
Make the tool your own by tweaking its appearance and functionality:
- Change Colors: Modify styles in the CSS block (e.g.,
.btn.primary { background: #0b72e7; }) to match your brand's color palette. - Adjust Layout: Update
.containerproperties likemax-widthorpaddingin the CSS to make it wider or narrower. - Change API: Extend the
shortenURLfunction to use a different shortening service API instead of TinyURL. You would just need to change thefetchURL and handle the response.
Why Use This URL Shortener Tool?
This tool stands out for its simplicity and all-in-one functionality. It's free, requires no complex installation, and works in any modern browser. Use it to create clean, trustworthy links for social media posts, email campaigns, or marketing materials. It enhances usability, makes your links look more professional, and can even boost engagement.
Practical Applications
You'd be surprised where this tool comes in handy:
- Marketing: Create short links for campaigns to make them easy to remember and type.
- Social Media: Fit long URLs into character-limited platforms like Twitter without sacrificing readability.
- Business: Use clean links in presentations, business cards, or customer support messages.
URL Shortener FAQs
What is a URL Shortener?
A URL Shortener is a tool that transforms a long web address (URL) into a shorter, more manageable link that redirects to the original page.
How do I install it on my website?
Simply copy the provided HTML, CSS, and JavaScript. Put the HTML in your <body>, the CSS in your <head> or stylesheet, and the JavaScript in a <script> tag.
Does this tool require a database?
No, this tool is entirely client-side. It uses the free TinyURL API to create and store the short links, so no database is needed on your server.
Is it safe to use?
Yes, the tool is safe. It runs in your browser and communicates directly with the TinyURL and QuickChart APIs. For sensitive links, always ensure you trust the shortening service being used.
Final Thoughts
The URL Shortener Tool’s source code is a powerful resource for any developer looking to add a useful utility to their site. Its flexibility and simple structure empower you to build, customize, and deploy a robust shortening solution tailored to your vision. We hope you embrace this opportunity to enhance your projects with a tool that perfectly blends simplicity and innovation!