Changed around line 1
+ document.addEventListener('DOMContentLoaded', () => {
+ const asciiInput = document.getElementById('ascii-input');
+ const binaryOutput = document.getElementById('binary-output');
+ const convertBtn = document.getElementById('convert-btn');
+ const swapBtn = document.getElementById('swap-btn');
+ const copyBtn = document.getElementById('copy-btn');
+ const clearBtn = document.getElementById('clear-btn');
+
+ function textToBinary(text) {
+ return text.split('').map(char => {
+ return char.charCodeAt(0).toString(2).padStart(8, '0');
+ }).join(' ');
+ }
+
+ function binaryToText(binary) {
+ return binary.split(' ').map(bin => {
+ return String.fromCharCode(parseInt(bin, 2));
+ }).join('');
+ }
+
+ function convert() {
+ const input = asciiInput.value;
+ if (!input) return;
+
+ try {
+ const isBinary = /^[01\s]+$/.test(input);
+ if (isBinary) {
+ binaryOutput.value = binaryToText(input);
+ } else {
+ binaryOutput.value = textToBinary(input);
+ }
+ } catch (error) {
+ binaryOutput.value = 'Error: Invalid input';
+ }
+ }
+
+ convertBtn.addEventListener('click', convert);
+
+ swapBtn.addEventListener('click', () => {
+ const temp = asciiInput.value;
+ asciiInput.value = binaryOutput.value;
+ binaryOutput.value = temp;
+ });
+
+ copyBtn.addEventListener('click', async () => {
+ try {
+ await navigator.clipboard.writeText(binaryOutput.value);
+ copyBtn.textContent = 'Copied!';
+ setTimeout(() => {
+ copyBtn.textContent = 'Copy';
+ }, 2000);
+ } catch (err) {
+ console.error('Failed to copy text:', err);
+ }
+ });
+
+ clearBtn.addEventListener('click', () => {
+ asciiInput.value = '';
+ binaryOutput.value = '';
+ });
+
+ // Auto-convert as user types (with debounce)
+ let timeout;
+ asciiInput.addEventListener('input', () => {
+ clearTimeout(timeout);
+ timeout = setTimeout(convert, 500);
+ });
+
+ // Handle keyboard shortcuts
+ document.addEventListener('keydown', (e) => {
+ if (e.ctrlKey || e.metaKey) {
+ if (e.key === 'Enter') {
+ e.preventDefault();
+ convert();
+ }
+ }
+ });
+ });