Let's Build a Text Comparison Tool (Using HTML, CSS, JS)

Published: March 19, 2024

1. What is a Text Comparison Tool?

A text comparison tool (Text Diff Tool) is a useful utility that displays differences between two texts. It's used by developers, document editors, students, and many others for comparing code or checking document revisions.

2. Required Technology Stack

  • HTML: Define the basic structure
  • CSS: Styling
  • JavaScript: Implement comparison logic

3. Create Basic HTML Structure

First, let's write the HTML for two text input areas and a compare button.

<textarea id="text1"></textarea>
<textarea id="text2"></textarea>
<button onclick="compareText()">Compare</button>
<div id="result"></div>

4. Implement Comparison Logic with JavaScript

Let's write a simple script that compares text line by line and highlights different lines.

function compareText() {
  const text1 = document.getElementById('text1').value.split('\n');
  const text2 = document.getElementById('text2').value.split('\n');
  
  let result = '';

  const maxLines = Math.max(text1.length, text2.length);

  for (let i = 0; i < maxLines; i++) {
    const line1 = text1[i] || '';
    const line2 = text2[i] || '';

    if (line1 === line2) {
      result += '<div>' + line1 + '</div>';
    } else {
      result += '<div style="background:#ffe0e0">' + line1 + ' ≠ ' + line2 + '</div>';
    }
  }

  document.getElementById('result').innerHTML = result;
}

5. Add Simple CSS

Let's add some styles to make the input areas and result window look better.

textarea {
  width: 45%;
  height: 150px;
  margin: 5px;
}
#result {
  margin-top: 20px;
  padding: 10px;
  border: 1px solid #ccc;
}

6. Conclusion

Now you have a simple text comparison tool! As you can see, you can create practical tools using just HTML, CSS, and JavaScript. Building such tools is a great way to improve your frontend development skills.