Building a Text Highlighting Tool for Web Pages: Step-by-Step Guide
Are you looking to enhance user experience on your website by implementing a text highlighting feature for search functionality? Well, you’re in luck! In this tutorial, we’ll walk through the process of creating a simple yet effective text highlighting tool using JavaScript and HTML. By the end, you’ll have a functional search mechanism that highlights all occurrences of a search query within a paragraph.
Step 1: Set Up Your HTML Structure
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Search Text Highlighter</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<input type="text" id="text-to-search" placeholder="Search...">
<button onclick="search()">Search</button>
<div id="result"></div>
<p id="paragraph">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla facilisi. Duis vestibulum hendrerit tortor, sed rhoncus nunc. Donec non ante vel quam vestibulum viverra. Sed sed posuere leo. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Suspendisse potenti. Vestibulum pharetra ex eget sapien pharetra, sit amet vestibulum velit laoreet. Vivamus sit amet felis vitae mi gravida cursus. Proin bibendum, purus a laoreet mattis, eros justo tincidunt justo, nec vestibulum magna purus non nisl. Proin sed arcu eget ligula auctor sagittis ac non massa. Integer nec urna ut orci lobortis rutrum. Mauris efficitur libero a risus pretium, non luctus nulla fermentum. Sed bibendum vehicula lacus, vel interdum turpis vulputate vel.</p>
</div>
<script src="Search-Text-Highlighter.js"></script>
</body>
</html>
Step 2: Style Your Web Page
body {
font-family: Arial, sans-serif;
background-color: #f5f5f5;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.container {
background-color: #fff;
border-radius: 8px;
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
padding: 20px;
max-width: 600px;
width: 100%;
text-align: center;
}
input[type="text"] {
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
margin-right: 10px;
width: 70%;
}
button {
padding: 10px 20px;
background-color: #4caf50;
color: #fff;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s ease;
}
button:hover {
background-color: #45a049;
}
#result {
margin-top: 10px;
font-weight: bold;
}
mark {
background-color: yellow;
font-weight: bold;
}
.no-result {
color: red;
}
.result-found {
color: green;
}
Step 3: JavaScript Function for Searching and Highlighting
// Function to perform search and highlight
function search() {
// Retrieve search query and paragraph element
let textToSearch = document.getElementById("text-to-search").value;
let paragraph = document.getElementById("paragraph");
// Escape special characters in search query
textToSearch = textToSearch.replace(/[.*+?^${}()\[\]\\]/g, "\\$&");
// Create regular expression pattern with search query
let pattern = new RegExp(textToSearch, "gi");
// Find all matches in paragraph text
let matches = paragraph.textContent.match(pattern);
// Get result div
let resultDiv = document.getElementById("result");
// Check if matches were found
if (matches && matches.length > 0) {
// Highlight matching text in paragraph
paragraph.innerHTML = paragraph.textContent.replace(
pattern,
(match) => `<mark>${match}</mark>`
);
// Display number of matches and apply green color
resultDiv.textContent = matches.length + " result(s) found.";
resultDiv.className = "result-found";
} else {
// Reset paragraph content and display no results message in red color
paragraph.innerHTML = paragraph.textContent;
resultDiv.textContent = "No results found.";
resultDiv.className = "no-result";
}
}
JavaScript function search()
performs the following actions:
- Retrieve Search Query and Paragraph Element: It fetches the search query entered by the user from the input field with the ID “text-to-search” and gets the paragraph element with the ID “paragraph” where the search operation will be conducted.
- Escape Special Characters: The function escapes special characters in the search query using a regular expression to ensure that the search query is treated as a literal string and not as a part of the regular expression pattern.
- Create Regular Expression Pattern: It constructs a regular expression pattern using the escaped search query with the global (g) and case-insensitive (i) flags. This pattern will be used to search for all occurrences of the search query within the paragraph.
- Find All Matches: The function searches for all matches of the regular expression pattern within the text content of the paragraph.
- Display Results: Depending on whether matches are found:
- If matches are found, it replaces each match within the paragraph’s text content with the same match wrapped in
<mark>
tags to highlight it. - It updates the content of the result div with the number of matches found and applies a green color style class.
- If no matches are found, it resets the paragraph’s content to its original state and displays a message indicating that no results were found, applying a red color style class to the result div.
Step 4: Testing Your Text Highlighting Tool
Before deploying your text highlighting tool to a live website or application, it’s crucial to thoroughly test its functionality to ensure that it performs as expected across different scenarios. Here’s how you can test your tool:
- Enter various search queries in the input field, including single words, phrases, and special characters.
- Click the “Search” button and observe if the tool correctly highlights all occurrences of the search query within the paragraph.
- Verify that the result message displays the correct number of matches found.
- Test with empty search query input to ensure the tool handles it gracefully and doesn’t cause unexpected behavior.
- Test with a search query that doesn’t match any text within the paragraph to verify that the tool correctly displays a message indicating no results found.
Congratulations! You’ve successfully built a Text Highlighting Tool using JavaScript. Feel free to customize and extend it further to suit your needs.
Conclusion
In this tutorial, we’ve learned how to create a text highlighting tool for web pages using JavaScript and HTML. By following the step-by-step guide, you’ve successfully implemented a search functionality that allows users to search for specific text within a paragraph and highlights all occurrences dynamically.
By breaking down the process into manageable steps, you’ve gained insights into:
- Setting up the HTML structure to accommodate the search input, button, result display, and target paragraph.
- Styling the web page to enhance its appearance and user experience.
- Implementing a JavaScript function (
search()
) to perform the search operation, handle matches, and dynamically highlight them. - Providing feedback to users about the search results, whether matches were found or not.
This text highlighting tool enhances the usability of your web page by enabling users to quickly locate relevant information within a body of text. You can further customize and expand upon this functionality to meet the specific needs of your website or application.
But before you go, why not stay connected?
Follow Me: Connect with me on LinkedIn for more updates and insights.
GitHub: Explore my projects and contributions on GitHub. You can find the repository for this project here.
CodePen: Check out my latest projects on CodePen. You can find the live project for this Search Text Highlighter here.
Support Me: If you find this tool helpful and would like to support my work, consider buying me a coffee on Buy Me a Coffee.
That’s it for this tutorial. Happy coding! 🚀