JSFiddle - React, Tailwind, and code Playground

by yiiBoy

HTML

<div id="textArea" onclick="handleWordClick(event)">This is a sample text. Click on any word to increase its frequency.</div>

CSS

#textArea {
    border: 1px solid #ccc;
    padding: 10px;
    cursor: text;
}

.word {
    display: inline-block;
    margin: 0 2px;
    padding: 2px;
    cursor: pointer;
    transition: all 0.3s ease;
}

.low-frequency {
    font-size: 100%;
    color: blue;
}

.medium-frequency {
    font-size: 120%;
    color: green;
}

.high-frequency {
    font-size: 140%;
    color: red;
}

JavaScript

let wordFrequency = {};

document.addEventListener('DOMContentLoaded', function() {
    processText();
});

function processText() {
    const textArea = document.getElementById('textArea');
    const text = textArea.textContent;
    const words = text.split(/\s+/);
    textArea.innerHTML = '';

    words.forEach(word => {
        const span = document.createElement('span');
        span.textContent = word;
        span.className = 'word low-frequency';
        textArea.appendChild(span);
        textArea.appendChild(document.createTextNode(' '));
    });
}

function handleWordClick(event) {
    if (event.target.classList.contains('word')) {
        const word = event.target.textContent;
        wordFrequency[word] = (wordFrequency[word] || 0) + 1;
        updateWordAppearance(event.target);
    }
}

function updateWordAppearance(wordElement) {
    const word = wordElement.textContent;
    const frequency = wordFrequency[word];

    wordElement.classList.remove('low-frequency', 'medium-frequency', 'high-frequency');
    if (frequency < 5) {
        wordElement.classList.add('low-frequency');
    } else if (frequency >= 5 && frequency < 10) {
        wordElement.classList.add('medium-frequency');
    } else {
        wordElement.classList.add('high-frequency');
    }
}