Introduction:
As a web developer or website owner, ensuring that your website's links are valid and functioning properly is crucial for user experience and search engine optimization (SEO). In this tutorial, we'll create a simple link checker tool using HTML, CSS, and JavaScript.
What We'll Build:
Our link checker tool will:
Accept a URL input from the user
Validate the URL format
Send a HEAD request to the URL
Display the response status code
Code:
HTML
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Link Checker</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Link Checker</h1>
<form id="link-form">
<input type="url" id="link-input" placeholder="Enter URL" value="https://codecrafti.blogspot.com">
<button id="check-button">Check</button>
</form>
<div id="result"></div>
<script src="script.js"></script>
</body>
</html>
CSS
font-family: Arial, sans-serif;
margin: 20px;
}
#link-form {
width: 50%;
margin: 0 auto;
}
#link-input {
width: 70%;
height: 30px;
font-size: 18px;
padding: 10px;
border: 1px solid #ccc;
}
#check-button {
width: 20%;
height: 30px;
font-size: 18px;
background-color: #4CAF50;
color: #fff;
border: none;
cursor: pointer;
}
#result {
margin-top: 20px;
font-size: 24px;
font-weight: bold;
}
JavaScript
JavaScriptconst linkForm = document.getElementById('link-form');
const linkInput = document.getElementById('link-input');
const checkButton = document.getElementById('check-button');
const resultDiv = document.getElementById('result');
linkForm.addEventListener('submit', (e) => {
e.preventDefault();
const url = linkInput.value.trim();
if (!isValidUrl(url)) {
resultDiv.textContent = 'Invalid URL format.';
return;
}
checkLink(url)
.then((statusCode) => {
if (statusCode === 200) {
resultDiv.textContent = 'Link is valid.';
} else {
resultDiv.textContent = `Link returned ${statusCode} status code.`;
}
})
.catch((error) => {
resultDiv.textContent = `Error: ${error.message}`;
});
});
function isValidUrl(url) {
try {
new URL(url);
return true;
} catch (error) {
return false;
}
}
function checkLink(url) {
return fetch(url, { method: 'HEAD' })
.then((response) => response.status)
.catch((error) => {
throw new Error(`Failed to check link: ${error.message}`);
});
}
How It Works:
The user inputs a URL and clicks the "Check" button.
The JavaScript code validates the URL format using the isValidUrl
function.
If valid, the code sends a HEAD request to the URL using the fetch
API.
The response status code is displayed on the page.
Conclusion:
This simple link checker tool demonstrates the power of HTML, CSS, and JavaScript in building useful web applications. Feel free to modify and expand this code to suit your needs!
Future Enhancements:
Example Use Cases:
Check if a website is online: http://example.com
Verify a link on a webpage: https://example.com/about-us
Test API endpoints: https://api.example.com/users
0 Comments