skip to Main Content

I have a variable called text that has a number of strings that are meant to be paragraphs that are separated by <br><br>.

However, my code is not displaying the breaks.

Below is my minimally working code:

<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>

    <div id="content">
        <p id="textParagraph" style="display: none"></p>
      </div>
    </div>

    <script>
    // Initialize data structures and variables
    var wordDictionary = {};         // Dictionary to store words
        var selectedWords = {};          // Currently selected words
        var isMouseDown = false;         // Flag for mouse state
        var currentColor = '';           // Current highlight color
        var usedColors = new Set();      // Set of used colors
        // Available highlight colors
        var availableColors = ["yellow", "red", "blue", "green", "orange"]; 
        var highlights = {};             // Store highlighted words for each event
        var eventCounter = 0;            // Counter for events

        var text = "Lorem ipsum dolor sit amet, cu eum eros vitae persequeris, laudem possit nam ex. 
        Labore eloquentiam per an. Sit ex omnesque interpretaris, habeo tantas eos ad, ea eos ludus inciderint. 
        Facete tritani pro ei, vim evertitur liberavisse ex. Ridens indoctum duo cu, est utamur aliquando expetendis ne. <br><br>
        n
        Cum nusquam definiebas ex, id esse neglegentur cum, eu libris bonorum volumus vis. 
        Ius et quis omnis graeco, no his nullam perpetua dissentiet. 
        No vix possim scripserit consequuntur, te mnesarchum philosophia sed. 
        Ne mea putent iudicabit, in eam ipsum viris dicunt. Eum amet accommodare ex, sint malis adversarium at qui.";

        var textParagraph = document.getElementById("textParagraph");
        textParagraph.textContent = text;

         // Execute when the window is loaded
         window.onload = function () {
            var contentDiv = document.getElementById('content');
            var text = contentDiv.textContent.trim();
            var words = text.split(/s+/);

            // Populate wordDictionary with words and create span elements for each word
            for (var i = 0; i < words.length; i++) {
                wordDictionary[i] = words[i];
            }

            for (var i = 0; i < words.length; i++) {
                var wordElement = document.createElement('span');
                wordElement.textContent = words[i] + ' ';
                wordElement.dataset.index = i;
                wordElement.addEventListener('mousedown', handleMouseDown);
                contentDiv.appendChild(wordElement);
            }

            // Add mouseup event listener for handling mouse up events
            document.addEventListener('mouseup', handleMouseUp);
        };
        // Function to get a random highlight color
        function getRandomColor() {
            if (availableColors.length === 0) {
                availableColors = [...usedColors];
                usedColors.clear();
            }

            var randomIndex = Math.floor(Math.random() * availableColors.length);
            var color = availableColors.splice(randomIndex, 1)[0];
            usedColors.add(color);
            return color;
        }

        // Function to handle mouse down event on words
        function handleMouseDown(event) {
            isMouseDown = true;
            var index = event.target.dataset.index;
            var word = event.target.textContent.trim();

            if (!isHighlighted(index)) {
                selectedWords = {};
                selectedWords.startIndex = index;
                selectedWords.endIndex = index;

                selectedWords[index] = word;
                currentColor = getRandomColor();
                event.target.style.backgroundColor = currentColor;

                event.preventDefault();

                document.addEventListener('mousemove', handleMouseMove);
            }
        }

        // Function to handle mouse up event
        function handleMouseUp(event) {
            if (isMouseDown) {
                document.removeEventListener('mousemove', handleMouseMove);
                var highlightedWords = {};

                for (var index in selectedWords) {
                    if (index !== 'startIndex' && index !== 'endIndex') {
                        highlightedWords[index] = selectedWords[index];
                    }
                }

                eventCounter++;
                highlights[eventCounter] = highlightedWords;
                console.log(highlights);
            }

            isMouseDown = false;
        }

        // Function to handle mouse move event (word selection)
        function handleMouseMove(event) {
            if (isMouseDown) {
                var currentIndex = event.target.dataset.index;
                var startIndex = selectedWords.startIndex;
                var endIndex = selectedWords.endIndex;
                var contentDiv = document.getElementById('content');

                var newStartIndex = Math.min(startIndex, currentIndex);
                var newEndIndex = Math.max(endIndex, currentIndex);

                clearPreviousSelection();

                for (var i = newStartIndex; i <= newEndIndex; i++) {
                    selectedWords[i] = wordDictionary[i];
                }

                for (var i = newStartIndex + 1; i <= newEndIndex + 1; i++) {
                    contentDiv.children[i].style.backgroundColor = currentColor;
                }

                selectedWords.startIndex = newStartIndex;
                selectedWords.endIndex = newEndIndex;
            }
        }

        // Function to clear previously selected words
        function clearPreviousSelection() {
            var contentDiv = document.getElementById('content');

            for (var i in selectedWords) {
                if (i !== 'startIndex' && i !== 'endIndex') {
                    contentDiv.children[i].style.backgroundColor = '';
                    delete selectedWords[i];
                }
            }
        }

        // Function to check if a word is already highlighted
        function isHighlighted(index) {
            for (var eventKey in highlights) {
                var highlightedWords = highlights[eventKey];

                for (var wordIndex in highlightedWords) {
                    if (wordIndex === index) {
                        return true;
                    }
                }
            }

            return false;
        }

        // Function to clear all selections and reset
        function clearSelections() {
            var contentDiv = document.getElementById('content');
            var wordElements = contentDiv.getElementsByTagName('span');

            for (var i = 0; i < wordElements.length; i++) {
                wordElements[i].style.backgroundColor = '';
            }

            highlights = {};
            eventCounter = 0;
        }

        // Function to undo the last selection
        function undoSelection() {
            if (eventCounter > 0) {
                var lastHighlight = highlights[eventCounter];

                for (var index in lastHighlight) {
                    var wordIndex = parseInt(index);
                    var contentDiv = document.getElementById('content');

                    if (!isNaN(wordIndex)) {
                        contentDiv.children[wordIndex + 1].style.backgroundColor = '';
                    }
                }

                delete highlights[eventCounter];
                eventCounter--;
            }
        }

        // Add event listeners to the clear and undo buttons
        document.getElementById("removeHighlight").addEventListener("click", clearSelections);
        document.getElementById("undoHighlight").addEventListener("click", undoSelection);
    </script>
</body>
</html>

2

Answers


  1. If you want to preserve the paragraph breaks in your text variable, you should use innerHTML instead of textContent as textContent treats everything as plain text while innerHTML treats the content as HTML

    So, instead of using textParagraph.textContent = text;, try using textParagraph.innerHTML = text;

    Login or Signup to reply.
  2. you can also use insertAdjacentHTML() method

    more information Element: insertAdjacentHTML() method

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search