This JavaScript code snippet is designed to handle the functionality of "Read More" buttons on a webpage. Each button, when clicked, toggles the visibility of a corresponding section of text. The code assumes that there are multiple "Read More" buttons and expandable text sections on the page, each identified by the class names 'read-more' and 'expandable-text', respectively.
How It Works:
- Element Collection: The script starts by collecting all elements with the class 'read-more' into the readMoreBtns NodeList and all elements with the class 'expandable-text' into the expandableTexts NodeList.
- Loop Through Buttons: It then iterates through each button in the readMoreBtns NodeList.
- State Tracking: For each button, a variable isOpen is initialized to false, indicating that the expandable text is initially hidden.
- Event Listener: An event listener for the 'click' event is added to each button. When a button is clicked:
- It checks the isOpen state.
- If isOpen is false, it adds the class 'is-open' to the corresponding expandable text element, making it visible and sets isOpen to true.
- If isOpen is true, it removes the class 'is-open', hiding the text, and resets isOpen to false.
Usage:
Ensure that each "Read More" button is paired correctly with a corresponding expandable text element in the HTML structure, and that they are indexed identically in their respective NodeLists. This script will handle any number of such pairs on a page.