URL Shortener Tool
body {
font-family: Arial, sans-serif;
background-color: #f9f9f9;
margin: 0;
padding: 0;
}
.container {
max-width: 600px;
margin: 0 auto;
padding: 20px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
background-color: #ffffff;
}
h1 {
text-align: center;
color: #4CAF50;
}
.input-wrapper {
display: flex;
margin-bottom: 10px;
}
input[type="url"] {
flex: 1;
padding: 10px;
margin-right: 10px;
border: 1px solid #ccc;
border-radius: 4px;
}
button {
background-color: #4CAF50;
color: #ffffff;
border: none;
padding: 10px 20px;
cursor: pointer;
border-radius: 4px;
}
button:hover {
background-color: #45a049;
}
.result {
margin-top: 20px;
padding: 10px;
background-color: #f2f2f2;
border-radius: 4px;
display: none;
}
.result p {
margin: 0;
color: #333;
}
#shortenedLink {
color: #4CAF50;
}
document.getElementById('shortenButton').addEventListener('click', shortenUrl);
function shortenUrl() {
const originalUrl = document.getElementById('originalUrl').value.trim();
if (!validateUrl(originalUrl)) {
alert('Please enter a valid URL.');
return;
}
fetchShortenedUrl(originalUrl);
}
function validateUrl(url) {
// Simple URL validation (requires the URL to start with 'http://' or 'https://')
return /^https?:\/\//i.test(url);
}
function fetchShortenedUrl(originalUrl) {
fetch(`https://api.shrtco.de/v2/shorten?url=${encodeURIComponent(originalUrl)}`)
.then(response => response.json())
.then(data => {
displayShortenedUrl(data);
})
.catch(error => {
console.error('Error fetching shortened URL:', error);
});
}
function displayShortenedUrl(data) {
const resultDiv = document.getElementById('result');
const shortenedLinkElement = document.getElementById('shortenedLink');
if (data.ok) {
shortenedLinkElement.href = data.result.full_short_link;
shortenedLinkElement.textContent = data.result.full_short_link;
resultDiv.style.display = 'block';
} else {
alert('Failed to shorten the URL. Please try again later.');
}
}
0 Comments