Read More Less Functionality
November 29, 2024 · AI Conversations
Lorem ipsum dolor sit amet consectur adipiscing elit sed eiu.
Read More
apply readmore/less in above div js
Here's an example of how you can do this:
1. Add an `id` or `class` to the description text (`p` tag) and the button so they can be easily targeted.
2. Use JavaScript to toggle the text visibility and the button text when clicked.
### Modified HTML:
<div class="elementor-element elementor-element-ebf09fe e-con-full readmore-less-div e-flex e-con e-child" data-id="ebf09fe" data-element_type="container">
<div class="elementor-element elementor-element-e5336ed elementor-widget elementor-widget-image" data-id="e5336ed" data-element_type="widget" data-widget_type="image.default">
<div class="elementor-widget-container">
<img fetchpriority="high" decoding="async" width="455" height="456" src="https://samh142.sg-host.com/wp-content/uploads/2024/11/Rectangle-1692.png" class="attachment-large size-large wp-image-4103" alt="" srcset="https://samh142.sg-host.com/wp-content/uploads/2024/11/Rectangle-1692.png 455w, https://samh142.sg-host.com/wp-content/uploads/2024/11/Rectangle-1692-300x300.png 300w, https://samh142.sg-host.com/wp-content/uploads/2024/11/Rectangle-1692-150x150.png 150w" sizes="(max-width: 455px) 100vw, 455px">
</div>
</div>
<div class="elementor-element elementor-element-8cf2725 elementor-widget elementor-widget-image-box" data-id="8cf2725" data-element_type="widget" data-widget_type="image-box.default">
<div class="elementor-widget-container">
<div class="elementor-image-box-wrapper">
<div class="elementor-image-box-content">
<h3 class="elementor-image-box-title">Full Name</h3>
<p class="elementor-image-box-description">CEO and Managing Director</p>
</div>
</div>
</div>
</div>
<div class="elementor-element elementor-element-a27bdab elementor-widget__width-initial elementor-widget-tablet_extra__width-inherit elementor-widget elementor-widget-text-editor" data-id="a27bdab" data-element_type="widget" data-widget_type="text-editor.default">
<div class="elementor-widget-container">
<p class="read-more-description">Lorem ipsum dolor sit amet consectur adipiscing elit sed eiu. Lorem ipsum dolor sit amet consectur adipiscing elit sed eiu. Lorem ipsum dolor sit amet consectur adipiscing elit sed eiu. Lorem ipsum dolor sit amet consectur adipiscing elit sed eiu.</p>
</div>
</div>
<div class="elementor-element elementor-element-a73edb0 elementor-align-center elementor-widget elementor-widget-button" data-id="a73edb0" data-element_type="widget" data-widget_type="button.default">
<div class="elementor-widget-container">
<div class="elementor-button-wrapper">
<a class="elementor-button elementor-button-link elementor-size-sm" href="javascript:void(0);" onclick="toggleReadMore()">
<span class="elementor-button-content-wrapper">
<span class="elementor-button-text" id="readMoreBtn">Read More</span>
</span>
</a>
</div>
</div>
</div>
</div>
### JavaScript:
function toggleReadMore() {
const description = document.querySelector('.read-more-description');
const buttonText = document.getElementById('readMoreBtn');
if (description.style.display === 'none') {
description.style.display = 'block';
buttonText.textContent = 'Read Less';
} else {
description.style.display = 'none';
buttonText.textContent = 'Read More';
}
}
// Initially hide the description text
document.addEventListener('DOMContentLoaded', function() {
const description = document.querySelector('.read-more-description');
description.style.display = 'none';
});
### Explanation:
1. **HTML Changes**:
– The long description is placed inside a “ element for easy targeting.
– The button now has an `onclick="toggleReadMore()"` attribute, which triggers the JavaScript function.
2. **JavaScript**:
– `toggleReadMore()` toggles the visibility of the description text and changes the button text between "Read More" and "Read Less".
– Initially, the description text is hidden (`display: none`) when the page loads.
### Styling (Optional):
If you want to add smooth transitions when toggling the description, you can add some CSS for the transition effect.
.read-more-description {
display: none;
transition: all 0.3s ease;
}
This setup will hide the text initially, and clicking the "Read More" button will reveal the description, changing the button text to "Read Less." Clicking again will hide the text and reset the button text.
### Modified HTML:
You don't need to change much in the HTML itself. The key is to initially hide the extra content and show the first 25 characters.
<div class="elementor-element elementor-element-ebf09fe e-con-full readmore-less-div e-flex e-con e-child" data-id="ebf09fe" data-element_type="container">
<div class="elementor-element elementor-element-e5336ed elementor-widget elementor-widget-image" data-id="e5336ed" data-element_type="widget" data-widget_type="image.default">
<div class="elementor-widget-container">
<img fetchpriority="high" decoding="async" width="455" height="456" src="https://samh142.sg-host.com/wp-content/uploads/2024/11/Rectangle-1692.png" class="attachment-large size-large wp-image-4103" alt="" srcset="https://samh142.sg-host.com/wp-content/uploads/2024/11/Rectangle-1692.png 455w, https://samh142.sg-host.com/wp-content/uploads/2024/11/Rectangle-1692-300x300.png 300w, https://samh142.sg-host.com/wp-content/uploads/2024/11/Rectangle-1692-150x150.png 150w" sizes="(max-width: 455px) 100vw, 455px">
</div>
</div>
<div class="elementor-element elementor-element-8cf2725 elementor-widget elementor-widget-image-box" data-id="8cf2725" data-element_type="widget" data-widget_type="image-box.default">
<div class="elementor-widget-container">
<div class="elementor-image-box-wrapper">
<div class="elementor-image-box-content">
<h3 class="elementor-image-box-title">Full Name</h3>
<p class="elementor-image-box-description">CEO and Managing Director</p>
</div>
</div>
</div>
</div>
<div class="elementor-element elementor-element-a27bdab elementor-widget__width-initial elementor-widget-tablet_extra__width-inherit elementor-widget elementor-widget-text-editor" data-id="a27bdab" data-element_type="widget" data-widget_type="text-editor.default">
<div class="elementor-widget-container">
<p class="read-more-description" id="descriptionText">Lorem ipsum dolor sit amet consectur adipiscing elit sed eiu. Lorem ipsum dolor sit amet consectur adipiscing elit sed eiu. Lorem ipsum dolor sit amet consectur adipiscing elit sed eiu. Lorem ipsum dolor sit amet consectur adipiscing elit sed eiu.</p>
</div>
</div>
<div class="elementor-element elementor-element-a73edb0 elementor-align-center elementor-widget elementor-widget-button" data-id="a73edb0" data-element_type="widget" data-widget_type="button.default">
<div class="elementor-widget-container">
<div class="elementor-button-wrapper">
<a class="elementor-button elementor-button-link elementor-size-sm" href="javascript:void(0);" onclick="toggleReadMore()">
<span class="elementor-button-content-wrapper">
<span class="elementor-button-text" id="readMoreBtn">Read More</span>
</span>
</a>
</div>
</div>
</div>
</div>
### Modified JavaScript:
This JavaScript will ensure that only the first 25 characters are displayed by default and the rest is hidden. When the "Read More" button is clicked, the entire text will be revealed, and the button will toggle to "Read Less".
“`javascript
function toggleReadMore() {
const description = document.getElementById('descriptionText');
const buttonText = document.getElementById('readMoreBtn');
// Toggle between showing full text and showing only the first 25 characters
if (description.classList.contains('expanded')) {
description.classList.remove('expanded');
description.innerHTML = description.getAttribute('data-short'); // Show short version
buttonText.textContent = 'Read More';
} else {
description.classList.add('expanded');
description.innerHTML = description.getAttribute('data-full'); // Show full text
buttonText.textContent = 'Read Less';
}
}
// Initially show only the first 25 characters and hide the rest
document.addEventListener('DOMContentLoaded', function() {
const description = document.getElementById('descriptionText');
const fullText = description.textContent;
Here’s how you can implement it:
### Modified HTML:
Keep the HTML structure the same, but you’ll need to adjust the description so that initially only the first 25 characters are shown, and the rest will be hidden until the user clicks "Read More."
### HTML:
<div class="elementor-element elementor-element-ebf09fe e-con-full readmore-less-div e-flex e-con e-child" data-id="ebf09fe" data-element_type="container">
<div class="elementor-element elementor-element-e5336ed elementor-widget elementor-widget-image" data-id="e5336ed" data-element_type="widget" data-widget_type="image.default">
<div class="elementor-widget-container">
<img fetchpriority="high" decoding="async" width="455" height="456" src="https://samh142.sg-host.com/wp-content/uploads/2024/11/Rectangle-1692.png" class="attachment-large size-large wp-image-4103" alt="" srcset="https://samh142.sg-host.com/wp-content/uploads/2024/11/Rectangle-1692.png 455w, https://samh142.sg-host.com/wp-content/uploads/2024/11/Rectangle-1692-300x300.png 300w, https://samh142.sg-host.com/wp-content/uploads/2024/11/Rectangle-1692-150x150.png 150w" sizes="(max-width: 455px) 100vw, 455px">
</div>
</div>
<div class="elementor-element elementor-element-8cf2725 elementor-widget elementor-widget-image-box" data-id="8cf2725" data-element_type="widget" data-widget_type="image-box.default">
<div class="elementor-widget-container">
<div class="elementor-image-box-wrapper">
<div class="elementor-image-box-content">
<h3 class="elementor-image-box-title">Full Name</h3>
<p class="elementor-image-box-description">CEO and Managing Director</p>
</div>
</div>
</div>
</div>
<div class="elementor-element elementor-element-a27bdab elementor-widget__width-initial elementor-widget-tablet_extra__width-inherit elementor-widget elementor-widget-text-editor" data-id="a27bdab" data-element_type="widget" data-widget_type="text-editor.default">
<div class="elementor-widget-container">
<p class="read-more-description">
Lorem ipsum dolor sit amet consectur adipiscing elit sed eiu. Lorem ipsum dolor sit amet consectur adipiscing elit sed eiu. Lorem ipsum dolor sit amet consectur adipiscing elit sed eiu. Lorem ipsum dolor sit amet consectur adipiscing elit sed eiu.
</p>
</div>
</div>
<div class="elementor-element elementor-element-a73edb0 elementor-align-center elementor-widget elementor-widget-button" data-id="a73edb0" data-element_type="widget" data-widget_type="button.default">
<div class="elementor-widget-container">
<div class="elementor-button-wrapper">
<a class="elementor-button elementor-button-link elementor-size-sm" href="javascript:void(0);" onclick="toggleReadMore()">
<span class="elementor-button-content-wrapper">
<span class="elementor-button-text" id="readMoreBtn">Read More</span>
</span>
</a>
</div>
</div>
</div>
</div>
### JavaScript:
Here's the updated JavaScript to show only the first 25 characters initially and toggle between "Read More" and "Read Less":
function toggleReadMore() {
const fullText = document.querySelector('.read-more-description');
const buttonText = document.getElementById('readMoreBtn');
if (fullText.classList.contains('expanded')) {
// If expanded, collapse the text and update the button
fullText.classList.remove('expanded');
buttonText.textContent = 'Read More';
} else {
// If collapsed, expand the text and update the button
fullText.classList.add('expanded');
buttonText.textContent = 'Read Less';
}
}
// Initially show only the first 25 characters of the description
document.addEventListener('DOMContentLoaded', function() {
const description = document.querySelector('.read-more-description');
const initialText = description.textContent.trim();
const truncatedText = initialText.substring(0, 25) + '...';
// Set the description to the truncated text
description.textContent = truncatedText;
// Add the ability to expand the text on click
description.addEventListener('click', function() {
description.classList.toggle('expanded');
toggleReadMore();
});
});
### CSS (Optional Styling):
You can add some styles to enhance the transition effect and control the default visibility of the description text.
.read-more-description {
transition: all 0.3s ease;
}
/* Initially show only the truncated text */
.read-more-description:not(.expanded) {
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* Expanded state */
.read-more-description.expanded {
white-space: normal;
}
/* Add smooth transition effect */
.read-more-description {
max-height: 100px;
overflow: hidden;
display: block;
}
### Explanation:
1. **HTML**: The description is initially truncated to 25 characters, and the "Read More" button will be shown.
2. **JavaScript**:
– On page load, the description text is truncated to 25 characters and an ellipsis (`…`) is added.
– The button toggles between "Read More" and "Read Less" based on the expanded state of the description.
3. **CSS**: The `read-more-description` class is set to show only the first 25 characters initially. When the description is expanded, it will display the full text.
When the page loads, the description will initially show only the first 25 characters, followed by an ellipsis. Clicking the "Read More" button will display the full text and change the button to "Read Less."
Here’s how you can adjust the code:
### Modified HTML:
No changes are needed to the HTML. You’ll just ensure that `.readmore-less-div` is the class you want to target.
<div class="elementor-element elementor-element-ebf09fe e-con-full readmore-less-div e-flex e-con e-child" data-id="ebf09fe" data-element_type="container">
<div class="elementor-element elementor-element-e5336ed elementor-widget elementor-widget-image" data-id="e5336ed" data-element_type="widget" data-widget_type="image.default">
<div class="elementor-widget-container">
<img fetchpriority="high" decoding="async" width="455" height="456" src="https://samh142.sg-host.com/wp-content/uploads/2024/11/Rectangle-1692.png" class="attachment-large size-large wp-image-4103" alt="" srcset="https://samh142.sg-host.com/wp-content/uploads/2024/11/Rectangle-1692.png 455w, https://samh142.sg-host.com/wp-content/uploads/2024/11/Rectangle-1692-300x300.png 300w, https://samh142.sg-host.com/wp-content/uploads/2024/11/Rectangle-1692-150x150.png 150w" sizes="(max-width: 455px) 100vw, 455px">
</div>
</div>
<div class="elementor-element elementor-element-8cf2725 elementor-widget elementor-widget-image-box" data-id="8cf2725" data-element_type="widget" data-widget_type="image-box.default">
<div class="elementor-widget-container">
<div class="elementor-image-box-wrapper">
<div class="elementor-image-box-content">
<h3 class="elementor-image-box-title">Full Name</h3>
<p class="elementor-image-box-description">CEO and Managing Director</p>
</div>
</div>
</div>
</div>
<div class="elementor-element elementor-element-a27bdab elementor-widget__width-initial elementor-widget-tablet_extra__width-inherit elementor-widget elementor-widget-text-editor" data-id="a27bdab" data-element_type="widget" data-widget_type="text-editor.default">
<div class="elementor-widget-container">
<p class="read-more-description">
Lorem ipsum dolor sit amet consectur adipiscing elit sed eiu. Lorem ipsum dolor sit amet consectur adipiscing elit sed eiu. Lorem ipsum dolor sit amet consectur adipiscing elit sed eiu. Lorem ipsum dolor sit amet consectur adipiscing elit sed eiu.
</p>
</div>
</div>
<div class="elementor-element elementor-element-a73edb0 elementor-align-center elementor-widget elementor-widget-button" data-id="a73edb0" data-element_type="widget" data-widget_type="button.default">
<div class="elementor-widget-container">
<div class="elementor-button-wrapper">
<a class="elementor-button elementor-button-link elementor-size-sm" href="javascript:void(0);" onclick="toggleReadMore(this)">
<span class="elementor-button-content-wrapper">
<span class="elementor-button-text" id="readMoreBtn">Read More</span>
</span>
</a>
</div>
</div>
</div>
</div>
### JavaScript:
We’ll now ensure that the "Read More/Read Less" logic only applies to the `.readmore-less-div` container and its contents.
function toggleReadMore(button) {
const container = button.closest('.readmore-less-div'); // Get the closest .readmore-less-div
const description = container.querySelector('.read-more-description');
const buttonText = container.querySelector('#readMoreBtn');
// Toggle the expanded state
if (description.classList.contains('expanded')) {
description.classList.remove('expanded');
buttonText.textContent = 'Read More';
} else {
description.classList.add('expanded');
buttonText.textContent = 'Read Less';
}
}
// Initially show only the first 25 characters of the description inside .readmore-less-div
document.addEventListener('DOMContentLoaded', function() {
const containers = document.querySelectorAll('.readmore-less-div'); // Target only .readmore-less-div containers
containers.forEach(container => {
const description = container.querySelector('.read-more-description');
const initialText = description.textContent.trim();
const truncatedText = initialText.substring(0, 25) + '...';
// Set the description to the truncated text
description.textContent = truncatedText;
// Add the ability to expand the text on click
container.querySelector('.read-more-description').addEventListener('click', function() {
description.classList.toggle('expanded');
toggleReadMore(container.querySelector('a'));
});
});
});
### Explanation of Changes:
1. **Targeting Specific Container (`.readmore-less-div`)**:
– The function `toggleReadMore(button)` now uses `button.closest('.readmore-less-div')` to find the closest parent container of the clicked button. This ensures that only the content inside the relevant `.readmore-less-div` container is affected.
2. **Selecting Only `.readmore-less-div` Elements**:
– When the page is loaded, `document.querySelectorAll('.readmore-less-div')` ensures that only elements with the class `.readmore-less-div` are processed.
3. **Updated Button and Description Targeting**:
– Inside the `toggleReadMore` function, both the description (`.read-more-description`) and button text (`#readMoreBtn`) are now targeted relative to their parent `.readmore-less-div` container. This avoids any conflicts if there are multiple instances of the button and description on the page.
4. **Initial Truncation**:
– Each `.readmore-less-div` container is processed individually, truncating the description to the first 25 characters and appending an ellipsis (`…`).
5. **Click Event for Expanding Text**:
– The click event listener is added to each `.readmore-less-div` container. When the "Read More" button is clicked, the description will expand or collapse accordingly, and the button text will toggle between "Read More" and "Read Less".
### Optional CSS:
To enhance the transitions and appearance, here’s a CSS snippet:
.read-more-description {
transition: all 0.3s ease;
}
/* Initially show only the truncated text */
.read-more-description:not(.expanded) {
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* Expanded state */
.read-more-description.expanded {
white-space: normal;
display: block;
}
### Result:
– The "Read More/Read Less" functionality will only apply to elements inside `.readmore-less-div`.
– Each `.readmore-less-div` will handle its own "Read More" button and description independently, ensuring isolated behavior across multiple instances.
Here's the updated approach that ensures the content inside the “ tag within `.elementor-widget-text-editor .elementor-widget-container` is handled correctly:
### Updated HTML (No changes needed here):
<div class="elementor-element elementor-element-ebf09fe e-con-full readmore-less-div e-flex e-con e-child" data-id="ebf09fe" data-element_type="container">
<div class="elementor-element elementor-element-e5336ed elementor-widget elementor-widget-image" data-id="e5336ed" data-element_type="widget" data-widget_type="image.default">
<div class="elementor-widget-container">
<img fetchpriority="high" decoding="async" width="455" height="456" src="https://samh142.sg-host.com/wp-content/uploads/2024/11/Rectangle-1692.png" class="attachment-large size-large wp-image-4103" alt="" srcset="https://samh142.sg-host.com/wp-content/uploads/2024/11/Rectangle-1692.png 455w, https://samh142.sg-host.com/wp-content/uploads/2024/11/Rectangle-1692-300x300.png 300w, https://samh142.sg-host.com/wp-content/uploads/2024/11/Rectangle-1692-150x150.png 150w" sizes="(max-width: 455px) 100vw, 455px">
</div>
</div>
<div class="elementor-element elementor-element-8cf2725 elementor-widget elementor-widget-image-box" data-id="8cf2725" data-element_type="widget" data-widget_type="image-box.default">
<div class="elementor-widget-container">
<div class="elementor-image-box-wrapper">
<div class="elementor-image-box-content">
<h3 class="elementor-image-box-title">Full Name</h3>
<p class="elementor-image-box-description">CEO and Managing Director</p>
</div>
</div>
</div>
</div>
<div class="elementor-element elementor-element-a27bdab elementor-widget__width-initial elementor-widget-tablet_extra__width-inherit elementor-widget elementor-widget-text-editor" data-id="a27bdab" data-element_type="widget" data-widget_type="text-editor.default">
<div class="elementor-widget-container">
<p class="read-more-description">
Lorem ipsum dolor sit amet consectur adipiscing elit sed eiu. Lorem ipsum dolor sit amet consectur adipiscing elit sed eiu. Lorem ipsum dolor sit amet consectur adipiscing elit sed eiu. Lorem ipsum dolor sit amet consectur adipiscing elit sed eiu.
</p>
</div>
</div>
<div class="elementor-element elementor-element-a73edb0 elementor-align-center elementor-widget elementor-widget-button" data-id="a73edb0" data-element_type="widget" data-widget_type="button.default">
<div class="elementor-widget-container">
<div class="elementor-button-wrapper">
<a class="elementor-button elementor-button-link elementor-size-sm" href="javascript:void(0);" onclick="toggleReadMore(this)">
<span class="elementor-button-content-wrapper">
<span class="elementor-button-text" id="readMoreBtn">Read More</span>
</span>
</a>
</div>
</div>
</div>
</div>
### Updated JavaScript:
Now the JavaScript will target the “ tag inside `.elementor-widget-text-editor .elementor-widget-container` to get the content and manage the "Read More/Read Less" functionality.
function toggleReadMore(button) {
const container = button.closest('.readmore-less-div'); // Get the closest .readmore-less-div
const description = container.querySelector('.elementor-widget-text-editor .elementor-widget-container p');
const buttonText = container.querySelector('#readMoreBtn');
// Toggle the expanded state
if (description.classList.contains('expanded')) {
description.classList.remove('expanded');
buttonText.textContent = 'Read More';
} else {
description.classList.add('expanded');
buttonText.textContent = 'Read Less';
}
}
// Initially show only the first 25 characters of the description inside .readmore-less-div
document.addEventListener('DOMContentLoaded', function() {
const containers = document.querySelectorAll('.readmore-less-div'); // Target only .readmore-less-div containers
containers.forEach(container => {
const description = container.querySelector('.elementor-widget-text-editor .elementor-widget-container p');
const initialText = description.textContent.trim();
const truncatedText = initialText.substring(0, 25) + '...';
// Set the description to the truncated text
description.textContent = truncatedText;
// Add the ability to expand the text on click
container.querySelector('.elementor-widget-text-editor .elementor-widget-container p').addEventListener('click', function() {
description.classList.toggle('expanded');
toggleReadMore(container.querySelector('a'));
});
});
});
### Explanation:
1. **Selecting Text Content (`.elementor-widget-text-editor .elementor-widget-container p`)**:
– The JavaScript now specifically selects the “ tag inside `.elementor-widget-text-editor .elementor-widget-container` for each `.readmore-less-div` container. This ensures only the content inside the specific text editor widget is modified.
2. **Truncating the Text**:
– The description is truncated to 25 characters by extracting a substring from the full text. The truncated content is then updated in the “ tag.
3. **Button Click Logic**:
– When the user clicks on the "Read More" button, it toggles the class `expanded` on the description “ element, either expanding or collapsing the full text.
– The button text toggles between "Read More" and "Read Less" based on whether the description is collapsed or expanded.
4. **Event Listener**:
– The event listener is added to the “ element directly, so when the text content is clicked, the `toggleReadMore` function is triggered.
### CSS (Optional):
To smoothly transition the appearance when expanding and collapsing the text, you can use this CSS:
.read-more-description {
transition: all 0.3s ease;
}
/* Initially show only the truncated text */
.read-more-description:not(.expanded) {
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* Expanded state */
.read-more-description.expanded {
white-space: normal;
display: block;
}
### Result:
– The "Read More/Read Less" functionality will now be applied specifically to the content inside `.elementor-widget-text-editor .elementor-widget-container p` within each `.readmore-less-div` container.
– The text is initially truncated to 25 characters, and users can click the "Read More" button to expand the content or collapse it again using "Read Less".
### Updated HTML:
Ensure that the `div` with class `.readmorebtn` wraps the anchor (“) that will trigger the "Read More/Read Less" functionality.
<div class="elementor-element elementor-element-ebf09fe e-con-full readmore-less-div e-flex e-con e-child" data-id="ebf09fe" data-element_type="container">
<div class="elementor-element elementor-element-e5336ed elementor-widget elementor-widget-image" data-id="e5336ed" data-element_type="widget" data-widget_type="image.default">
<div class="elementor-widget-container">
<img fetchpriority="high" decoding="async" width="455" height="456" src="https://samh142.sg-host.com/wp-content/uploads/2024/11/Rectangle-1692.png" class="attachment-large size-large wp-image-4103" alt="" srcset="https://samh142.sg-host.com/wp-content/uploads/2024/11/Rectangle-1692.png 455w, https://samh142.sg-host.com/wp-content/uploads/2024/11/Rectangle-1692-300x300.png 300w, https://samh142.sg-host.com/wp-content/uploads/2024/11/Rectangle-1692-150x150.png 150w" sizes="(max-width: 455px) 100vw, 455px">
</div>
</div>
<div class="elementor-element elementor-element-8cf2725 elementor-widget elementor-widget-image-box" data-id="8cf2725" data-element_type="widget" data-widget_type="image-box.default">
<div class="elementor-widget-container">
<div class="elementor-image-box-wrapper">
<div class="elementor-image-box-content">
<h3 class="elementor-image-box-title">Full Name</h3>
<p class="elementor-image-box-description">CEO and Managing Director</p>
</div>
</div>
</div>
</div>
<div class="elementor-element elementor-element-a27bdab elementor-widget__width-initial elementor-widget-tablet_extra__width-inherit elementor-widget elementor-widget-text-editor" data-id="a27bdab" data-element_type="widget" data-widget_type="text-editor.default">
<div class="elementor-widget-container">
<p class="read-more-description">
Lorem ipsum dolor sit amet consectur adipiscing elit sed eiu. Lorem ipsum dolor sit amet consectur adipiscing elit sed eiu. Lorem ipsum dolor sit amet consectur adipiscing elit sed eiu. Lorem ipsum dolor sit amet consectur adipiscing elit sed eiu.
</p>
</div>
</div>
<div class="elementor-element elementor-element-a73edb0 elementor-align-center elementor-widget elementor-widget-button" data-id="a73edb0" data-element_type="widget" data-widget_type="button.default">
<div class="elementor-widget-container">
<div class="readmorebtn"> <!-- The div wrapping the "Read More" button -->
<a href="javascript:void(0);" class="elementor-button elementor-button-link elementor-size-sm">
<span class="elementor-button-content-wrapper">
<span class="elementor-button-text" id="readMoreBtn">Read More</span>
</span>
</a>
</div>
</div>
</div>
</div>
### Updated JavaScript:
This script now targets the `.readmorebtn` div, listens for a click on the anchor (“) inside it, and performs the "Read More/Read Less" functionality.
function toggleReadMore(button) {
const container = button.closest('.readmore-less-div'); // Get the closest .readmore-less-div
const description = container.querySelector('.elementor-widget-text-editor .elementor-widget-container p');
const buttonText = container.querySelector('#readMoreBtn');
// Toggle the expanded state
if (description.classList.contains('expanded')) {
description.classList.remove('expanded');
buttonText.textContent = 'Read More';
} else {
description.classList.add('expanded');
buttonText.textContent = 'Read Less';
}
}
// Initially show only the first 25 characters of the description inside .readmore-less-div
document.addEventListener('DOMContentLoaded', function() {
const containers = document.querySelectorAll('.readmore-less-div'); // Target only .readmore-less-div containers
containers.forEach(container => {
const description = container.querySelector('.elementor-widget-text-editor .elementor-widget-container p');
const initialText = description.textContent.trim();
const truncatedText = initialText.substring(0, 25) + '...';
// Set the description to the truncated text
description.textContent = truncatedText;
// Add click event listener to the Read More button
const readMoreBtn = container.querySelector('.readmorebtn a');
readMoreBtn.addEventListener('click', function() {
description.classList.toggle('expanded');
toggleReadMore(readMoreBtn);
});
});
});
### Explanation of Changes:
1. **`toggleReadMore` Function**:
– This function still targets the `.readmore-less-div` container, but now it looks for the “ inside `.elementor-widget-text-editor .elementor-widget-container` to toggle the text between truncated and full content.
2. **Click Handler on `.readmorebtn a`**:
– We add an event listener to the anchor tag (“) inside the `.readmorebtn` div. When the button is clicked, it will toggle the text and change the button text to either "Read More" or "Read Less" accordingly.
3. **Truncation**:
– The text in the “ tag is truncated to the first 25 characters on page load.
4. **Text Expansion/Collapse**:
– When the "Read More" button is clicked, the text expands, and the button text switches to "Read Less". If the text is expanded and the button is clicked again, the text collapses, and the button text switches back to "Read More".
### Optional CSS for Smooth Transition:
You may want to add smooth transitions for the expanding and collapsing of the text:
.read-more-description {
transition: all 0.3s ease;
}
/* Initially show only the truncated text */
.read-more-description:not(.expanded) {
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* Expanded state */
.read-more-description.expanded {
white-space: normal;
display: block;
}
### Result:
– The "Read More/Read Less" functionality will work with the `div.readmorebtn` wrapping the anchor (“) tag.
– The content inside `.elementor-widget-text-editor .elementor-widget-container p` will be truncated to the first 25 characters by default and will expand or collapse on clicking the "Read More" button.
– The button text will toggle between "Read More" and "Read Less" based on the expanded or collapsed state of the content.
Here’s how you can do it in both ways:
### Method 1: Directly Add Script in `footer.php`
If you have access to your theme’s `footer.php` file, you can insert the JavaScript directly in the file inside the `wp_footer` action hook.
1. Open your `footer.php` file.
2. Inside the file, just before the closing “ tag, add the following code:
<?php wp_footer(); ?>
<script>
document.addEventListener('DOMContentLoaded', function() {
function toggleReadMore(button) {
const container = button.closest('.readmore-less-div'); // Get the closest .readmore-less-div
const description = container.querySelector('.elementor-widget-text-editor .elementor-widget-container p');
const buttonText = container.querySelector('#readMoreBtn');
// Toggle the expanded state
if (description.classList.contains('expanded')) {
description.classList.remove('expanded');
buttonText.textContent = 'Read More';
} else {
description.classList.add('expanded');
buttonText.textContent = 'Read Less';
}
}
// Initially show only the first 25 characters of the description inside .readmore-less-div
const containers = document.querySelectorAll('.readmore-less-div'); // Target only .readmore-less-div containers
containers.forEach(container => {
const description = container.querySelector('.elementor-widget-text-editor .elementor-widget-container p');
const initialText = description.textContent.trim();
const truncatedText = initialText.substring(0, 25) + '...';
// Set the description to the truncated text
description.textContent = truncatedText;
// Add click event listener to the Read More button
const readMoreBtn = container.querySelector('.readmorebtn a');
readMoreBtn.addEventListener('click', function() {
description.classList.toggle('expanded');
toggleReadMore(readMoreBtn);
});
});
});
</script>
</body>
</html>
This code will ensure that the JavaScript is loaded on every page where `wp_footer()` is used.
### Method 2: Add Script via `wp_add_inline_script()` in `functions.php`
Alternatively, you can add the script via `wp_add_inline_script()` inside your theme’s `functions.php` file. This method is cleaner and ensures that the JavaScript is included correctly without modifying the `footer.php` directly.
1. Open your theme’s `functions.php` file.
2. Add the following code to enqueue the script inline in the footer:
function custom_readmore_script() {
// Ensure the script is added only to the frontend
if (is_front_page() || is_single() || is_page()) {
?>
<script>
document.addEventListener('DOMContentLoaded', function() {
function toggleReadMore(button) {
const container = button.closest('.readmore-less-div'); // Get the closest .readmore-less-div
const description = container.querySelector('.elementor-widget-text-editor .elementor-widget-container p');
const buttonText = container.querySelector('#readMoreBtn');
// Toggle the expanded state
if (description.classList.contains('expanded')) {
description.classList.remove('expanded');
buttonText.textContent = 'Read More';
} else {
description.classList.add('expanded');
buttonText.textContent = 'Read Less';
}
}
// Initially show only the first 25 characters of the description inside .readmore-less-div
const containers = document.querySelectorAll('.readmore-less-div'); // Target only .readmore-less-div containers
containers.forEach(container => {
const description = container.querySelector('.elementor-widget-text-editor .elementor-widget-container p');
const initialText = description.textContent.trim();
const truncatedText = initialText.substring(0, 25) + '...';
// Set the description to the truncated text
description.textContent = truncatedText;
// Add click event listener to the Read More button
const readMoreBtn = container.querySelector('.readmorebtn a');
readMoreBtn.addEventListener('click', function() {
description.classList.toggle('expanded');
toggleReadMore(readMoreBtn);
});
});
});
</script>
<?php
}
}
add_action('wp_footer', 'custom_readmore_script');
### Explanation:
– **Method 1 (`footer.php`)**: This method directly adds the JavaScript in the `footer.php` file before the closing “ tag. `wp_footer()` must be called in the theme's `footer.php` to ensure WordPress runs any scripts hooked to `wp_footer`.
– **Method 2 (`functions.php`)**: This method uses `wp_add_inline_script()` to dynamically add JavaScript to the footer of the page. This is a cleaner approach and keeps the theme’s files more maintainable. The `add_action('wp_footer', 'custom_readmore_script')` ensures that the script is included before the closing “ tag of the page.
### Additional Notes:
– **Performance**: Both methods will add the JavaScript just before the closing “ tag, which is optimal for performance, as it allows the page to load the HTML and CSS first, avoiding blocking rendering.
– **Conditional Loading**: In the `functions.php` method, you can customize the `if` condition to load the script only on specific pages if needed, like `is_single()` for posts, `is_page()` for specific pages, or `is_front_page()` for the homepage.
### Result:
– This approach will ensure that your "Read More/Read Less" JavaScript is added to the footer of every page where `wp_footer()` is present (Method 1) or dynamically through the `wp_footer` action (Method 2).
– It will work seamlessly with the `div.readmorebtn` wrapping the anchor (“) tag for the "Read More" button.
### Updated JavaScript:
In this updated version, the JavaScript will target the “ tag directly and replace its inner text between "Read More" and "Read Less".
### Updated Code:
function custom_readmore_script() {
// Ensure the script is added only to the frontend
if (is_front_page() || is_single() || is_page()) {
?>
<script>
document.addEventListener('DOMContentLoaded', function() {
// Function to toggle Read More / Read Less
function toggleReadMore(button) {
const container = button.closest('.readmore-less-div'); // Get the closest .readmore-less-div
const description = container.querySelector('.elementor-widget-text-editor .elementor-widget-container p');
// Toggle the expanded state
if (description.classList.contains('expanded')) {
description.classList.remove('expanded');
button.textContent = 'Read More'; // Change the button text to "Read More"
} else {
description.classList.add('expanded');
button.textContent = 'Read Less'; // Change the button text to "Read Less"
}
}
// Initially show only the first 25 characters of the description inside .readmore-less-div
const containers = document.querySelectorAll('.readmore-less-div'); // Target only .readmore-less-div containers
containers.forEach(container => {
const description = container.querySelector('.elementor-widget-text-editor .elementor-widget-container p');
const initialText = description.textContent.trim();
const truncatedText = initialText.substring(0, 25) + '...';
// Set the description to the truncated text
description.textContent = truncatedText;
// Add click event listener to the Read More button
const readMoreBtn = container.querySelector('.readmorebtn a');
readMoreBtn.addEventListener('click', function() {
description.classList.toggle('expanded');
toggleReadMore(readMoreBtn);
});
});
});
</script>
<?php
}
}
add_action('wp_footer', 'custom_readmore_script');
### Explanation:
– **`toggleReadMore` function**: Now, instead of changing a separate element with `#readMoreBtn`, we directly modify the text of the “ tag (`button.textContent`). If the description is expanded, it changes the text to "Read Less". If collapsed, it changes the text to "Read More".
– **Click Handler**: The event listener is added to the “ tag within the `.readmorebtn` container. When clicked, it toggles the text and the description’s expanded state.
### Notes:
– **`textContent`**: The `button.textContent` refers to the anchor tag (“) itself, so when you click the "Read More" or "Read Less" link, it will change its own text.
– **CSS**: The `description.classList.toggle('expanded')` will allow toggling between truncated and full text. Make sure the CSS reflects that change, as shown in the previous answer.
### Example of how the HTML should look:
<div class="elementor-element elementor-element-ebf09fe e-con-full readmore-less-div e-flex e-con e-child" data-id="ebf09fe" data-element_type="container">
<div class="elementor-element elementor-element-e5336ed elementor-widget elementor-widget-image" data-id="e5336ed" data-element_type="widget" data-widget_type="image.default">
<div class="elementor-widget-container">
<img fetchpriority="high" decoding="async" width="455" height="456" src="https://samh142.sg-host.com/wp-content/uploads/2024/11/Rectangle-1692.png" class="attachment-large size-large wp-image-4103" alt="" srcset="https://samh142.sg-host.com/wp-content/uploads/2024/11/Rectangle-1692.png 455w, https://samh142.sg-host.com/wp-content/uploads/2024/11/Rectangle-1692-300x300.png 300w, https://samh142.sg-host.com/wp-content/uploads/2024/11/Rectangle-1692-150x150.png 150w" sizes="(max-width: 455px) 100vw, 455px">
</div>
</div>
<div class="elementor-element elementor-element-8cf2725 elementor-widget elementor-widget-image-box" data-id="8cf2725" data-element_type="widget" data-widget_type="image-box.default">
<div class="elementor-widget-container">
<div class="elementor-image-box-wrapper">
<div class="elementor-image-box-content">
<h3 class="elementor-image-box-title">Full Name</h3>
<p class="elementor-image-box-description">CEO and Managing Director</p>
</div>
</div>
</div>
</div>
<div class="elementor-element elementor-element-a27bdab elementor-widget__width-initial elementor-widget-tablet_extra__width-inherit elementor-widget elementor-widget-text-editor" data-id="a27bdab" data-element_type="widget" data-widget_type="text-editor.default">
<div class="elementor-widget-container">
<p class="read-more-description">
Lorem ipsum dolor sit amet consectur adipiscing elit sed eiu. Lorem ipsum dolor sit amet consectur adipiscing elit sed eiu. Lorem ipsum dolor sit amet consectur adipiscing elit sed eiu. Lorem ipsum dolor sit amet consectur adipiscing elit sed eiu.
</p>
</div>
</div>
<div class="elementor-element elementor-element-a73edb0 elementor-align-center elementor-widget elementor-widget-button" data-id="a73edb0" data-element_type="widget" data-widget_type="button.default">
<div class="elementor-widget-container">
<div class="readmorebtn"> <!-- The div wrapping the "Read More" button -->
<a href="javascript:void(0);" class="elementor-button elementor-button-link elementor-size-sm">
<span class="elementor-button-content-wrapper">
<span class="elementor-button-text">Read More</span>
</span>
</a>
</div>
</div>
</div>
</div>
### CSS for Transition and Truncation:
Make sure you have this CSS in place to properly handle the truncation and expansion of the description text.
.read-more-description {
transition: all 0.3s ease;
}
/* Initially show only the truncated text */
.read-more-description:not(.expanded) {
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* Expanded state */
.read-more-description.expanded {
white-space: normal;
display: block;
}
### Result:
– The "Read More" text will toggle to "Read Less" directly inside the “ tag when clicked.
– The description will initially be truncated to the first 25 characters, and it will expand to show the full content when the "Read More" button is clicked.
readMoreBtn.addEventListener('click', function() {
description.classList.toggle('expanded');
toggleReadMore(readMoreBtn);
});
above not adding expand class
### Updated Code
Here’s an updated version with some checks and refinements:
1. **Ensure the `description` is correctly selected.**
2. **Correctly handle the class toggle for expanding/collapsing the text.**
3. **Ensure the button text toggles between "Read More" and "Read Less" properly.**
function custom_readmore_script() {
// Ensure the script is added only to the frontend
if (is_front_page() || is_single() || is_page()) {
?>
<script>
document.addEventListener('DOMContentLoaded', function() {
// Function to toggle Read More / Read Less text
function toggleReadMore(button) {
const container = button.closest('.readmore-less-div'); // Get the closest .readmore-less-div
const description = container.querySelector('.elementor-widget-text-editor .elementor-widget-container p');
// Toggle the expanded state
if (description.classList.contains('expanded')) {
description.classList.remove('expanded'); // Remove expanded class to collapse text
button.textContent = 'Read More'; // Change the button text to "Read More"
} else {
description.classList.add('expanded'); // Add expanded class to show full text
button.textContent = 'Read Less'; // Change the button text to "Read Less"
}
}
// Initially show only the first 25 characters of the description inside .readmore-less-div
const containers = document.querySelectorAll('.readmore-less-div'); // Target only .readmore-less-div containers
containers.forEach(container => {
const description = container.querySelector('.elementor-widget-text-editor .elementor-widget-container p');
if (description) {
const initialText = description.textContent.trim();
const truncatedText = initialText.substring(0, 25) + '...';
// Set the description to the truncated text initially
description.textContent = truncatedText;
// Add click event listener to the Read More button
const readMoreBtn = container.querySelector('.readmorebtn a');
if (readMoreBtn) {
readMoreBtn.addEventListener('click', function(e) {
e.preventDefault(); // Prevent any default action
description.classList.toggle('expanded'); // Toggle expanded class
toggleReadMore(readMoreBtn); // Toggle the button text between Read More / Read Less
});
}
}
});
});
</script>
<?php
}
}
add_action('wp_footer', 'custom_readmore_script');
### Key Changes:
1. **Check if `description` exists**: We now ensure that `description` exists before attempting to manipulate it. This ensures the script doesn't fail if the `p` tag is missing in some instances.
2. **Prevent default link behavior**: I added `e.preventDefault();` to the click event handler to stop the default behavior of the anchor tag (e.g., navigating to a new page or jumping to a link), especially if the link is not intended to go anywhere (`href="#"`).
3. **Toggle class and button text**: The `toggleReadMore` function is directly toggling the button text and the `expanded` class on the `description` element.
### CSS for Expanding/Collapsing Text:
Make sure you have the following CSS to handle the truncation and expansion:
.read-more-description {
transition: all 0.3s ease;
}
/* Initially show only the truncated text */
.read-more-description:not(.expanded) {
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* Expanded state */
.read-more-description.expanded {
white-space: normal;
display: block;
}
### Explanation:
– **Truncation**: Initially, the text is truncated to the first 25 characters with an ellipsis (`…`).
– **Expanding**: When the "Read More" button is clicked, the `expanded` class is added, which allows the full text to be shown.
– **Button Text Toggle**: The text of the button (`Read More` and `Read Less`) toggles between the two states.
### Result:
– When you load the page, the description text will be truncated to 25 characters by default.
– When you click "Read More", the text expands, and the button text changes to "Read Less".
– When you click "Read Less", the text collapses back to 25 characters, and the button text changes back to "Read More".
This should work as expected now!
### Breakdown:
– **`description.classList`**: This is a property of the `description` element (which is a DOM node, typically a “ element in your case). The `classList` property provides access to the list of classes assigned to the element. It allows you to manipulate the classes easily.
– **`toggle()`**: The `toggle()` method is used to **add** a class to an element if it doesn't already exist, and **remove** it if it does. In other words, it "toggles" the presence of the specified class.
– **`'expanded'`**: This is the class that you're toggling. If the `description` element already has the `expanded` class, it will be removed; if it doesn't have it, the class will be added.
### What this does:
– When the `toggle()` method is called on `description.classList`, it checks if the `expanded` class is present on the `description` element.
– **If the `expanded` class is not present**, it adds it, which can be used to apply specific CSS rules for the expanded state (like showing the full text).
– **If the `expanded` class is present**, it removes it, which could trigger a CSS rule that hides part of the text again (e.g., truncating it).
### Example:
Let’s assume you have the following CSS:
.read-more-description {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-height: 50px; /* Truncated height */
transition: max-height 0.3s ease; /* Smooth transition */
}
.read-more-description.expanded {
white-space: normal; /* Allow text to wrap */
overflow: visible; /* Show the full content */
max-height: none; /* No height limit when expanded */
}
And your HTML might look like this:
<p class="read-more-description">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus viverra metus eu arcu malesuada, in volutpat arcu sollicitudin.</p>
<button class="read-more-btn">Read More</button>
### Behavior with `toggle()`:
– Initially, the paragraph will show only a truncated version of the text due to the `.read-more-description` styles.
– When you click the "Read More" button, the `expanded` class will be added to the paragraph (“), allowing the full text to be shown.
– If the button is clicked again, the `expanded` class will be removed, and the text will be truncated again.
### Practical Example in Code:
Here’s a simple example using the `toggle()` method:
<div class="description-container">
<p class="read-more-description">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus viverra metus eu arcu malesuada, in volutpat arcu sollicitudin.</p>
<button class="read-more-btn">Read More</button>
</div>
<script>
document.querySelector('.read-more-btn').addEventListener('click', function() {
const description = document.querySelector('.read-more-description');
description.classList.toggle('expanded'); // Toggle the 'expanded' class on the paragraph
});
</script>
### Key Points:
– **No `expanded` class**: The text is truncated.
– **With `expanded` class**: The text is fully visible (based on your CSS rules).
This toggle mechanism is what enables the "Read More/Read Less" functionality: it shows more or less content dynamically based on the user’s interaction with the button.
### 1. Ensure the `description` element is selected correctly
First, make sure that the `description` variable is correctly targeting the element you're expecting.
### 2. Verify the class is being toggled
You can debug by logging the class list of the `description` element before and after toggling the class.
### 3. Make sure the `description` element exists
If you're selecting an element inside the `.readmore-less-div` container, confirm that it’s being found. If the `querySelector` isn't finding the element, `description` will be `null`, and the `toggle()` won't work.
Here’s how to update your code to add some debugging checks:
### Updated Code with Debugging:
function custom_readmore_script() {
// Ensure the script is added only to the frontend
if (is_front_page() || is_single() || is_page()) {
?>
<script>
document.addEventListener('DOMContentLoaded', function() {
// Function to toggle Read More / Read Less text
function toggleReadMore(button) {
const container = button.closest('.readmore-less-div'); // Get the closest .readmore-less-div
const description = container.querySelector('.elementor-widget-text-editor .elementor-widget-container p');
// Debugging: Check if description is found
console.log(description); // Log the description element
// Check if the description exists before trying to toggle class
if (description) {
// Debugging: Check the class list before and after toggle
console.log('Before toggle:', description.classList); // Log class list before toggle
description.classList.toggle('expanded'); // Toggle the expanded class
console.log('After toggle:', description.classList); // Log class list after toggle
}
}
// Initially show only the first 25 characters of the description inside .readmore-less-div
const containers = document.querySelectorAll('.readmore-less-div'); // Target only .readmore-less-div containers
containers.forEach(container => {
const description = container.querySelector('.elementor-widget-text-editor .elementor-widget-container p');
if (description) {
const initialText = description.textContent.trim();
const truncatedText = initialText.substring(0, 25) + '...';
// Set the description to the truncated text initially
description.textContent = truncatedText;
// Add click event listener to the Read More button
const readMoreBtn = container.querySelector('.readmorebtn a');
if (readMoreBtn) {
readMoreBtn.addEventListener('click', function(e) {
e.preventDefault(); // Prevent any default action
description.classList.toggle('expanded'); // Toggle expanded class
toggleReadMore(readMoreBtn); // Toggle the button text between Read More / Read Less
});
}
}
});
});
</script>
<?php
}
}
add_action('wp_footer', 'custom_readmore_script');
### What’s New:
1. **Console logs**:
– `console.log(description)` will log the `description` element to see if it’s being selected correctly.
– `console.log('Before toggle:', description.classList)` and `console.log('After toggle:', description.classList)` will print the class list before and after the `expanded` class is toggled.
### Debugging Steps:
1. Open your browser’s Developer Tools (press `F12` or `Ctrl + Shift + I` in most browsers).
2. Go to the **Console** tab.
3. Click the "Read More" button on your page and check the console output.
– If the `description` element is `null`, that means the `querySelector` isn't finding the paragraph element (`p`).
– If the `expanded` class is not being toggled, the class list before and after the toggle should provide clues.
### Possible Issues:
1. **`description` is `null`**: This could happen if the `.elementor-widget-text-editor .elementor-widget-container p` selector doesn’t match the element correctly. Double-check your HTML structure and make sure the element exists when the script runs.
– To troubleshoot, you can try logging the `container` to ensure it’s being found:
console.log(container);
2. **`classList.toggle` isn't working**: If you are still having issues, it's possible there is a CSS or JS issue preventing the class from being applied. Check if there are any errors in the console.
### Example Console Output:
After clicking the "Read More" button, the console should show something like this:
<p class="elementor-widget-text-editor...">Lorem ipsum dolor sit amet...</p>
Before toggle: DOMTokenList(2) ["read-more-description", value: "read-more-description"]
After toggle: DOMTokenList(3) ["read-more-description", "expanded", value: "read-more-description expanded"]
This will indicate that the class was successfully toggled.
### CSS for `expanded`:
To make sure the expansion works, you need to have proper CSS for the `.expanded` class:
.read-more-description {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-height: 50px; /* Truncated height */
transition: max-height 0.3s ease;
}
/* Expanded text will show fully */
.read-more-description.expanded {
white-space: normal;
overflow: visible;
max-height: none;
}
Let me know the console output after you try this, and I can help you refine further if needed!
1. **The extra text isn't showing when "Read More" is clicked.**
2. **The "Read More" text isn't changing to "Read Less".**
Let’s go step-by-step to fix both issues.
### Problem 1: Extra Text Not Showing
The reason the extra text isn't showing could be due to CSS or how the text is being toggled. We need to ensure the following:
1. The truncated text should be limited by a `max-height` or other CSS properties until the user clicks "Read More".
2. The full text should be shown when the `expanded` class is added.
### Problem 2: "Read More" Text Not Changing to "Read Less"
We also need to ensure that the text of the button (`Read More` / `Read Less`) is correctly toggling when clicked.
### Updated Code to Fix Both Issues
#### 1. **HTML Structure** (just for reference, no changes):
<div class="readmore-less-div">
<div class="elementor-widget-text-editor">
<div class="elementor-widget-container">
<p class="read-more-description">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus viverra metus eu arcu malesuada, in volutpat arcu sollicitudin. Curabitur vehicula magna id velit sollicitudin, non facilisis eros egestas.</p>
</div>
</div>
<div class="readmorebtn">
<a href="#">Read More</a>
</div>
</div>
#### 2. **CSS** (for truncating and expanding the text):
You need to make sure the description is initially truncated, and the expansion works when the `expanded` class is added.
.read-more-description {
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-height: 50px; /* Truncated height */
transition: all 0.3s ease; /* Smooth transition */
}
/* When expanded, show the full text */
.read-more-description.expanded {
white-space: normal; /* Allow text to wrap */
overflow: visible; /* Show the full content */
max-height: none; /* No height limit when expanded */
}
/* Optionally style the Read More/Read Less button */
.readmorebtn a {
color: #007bff;
cursor: pointer;
text-decoration: none;
}
#### 3. **JavaScript** (to toggle the text and button correctly):
Here's an updated script to correctly handle both the text expansion and the button text change. We're ensuring that the text content of the button changes between "Read More" and "Read Less" when clicked.
function custom_readmore_script() {
// Ensure the script is added only to the frontend
if (is_front_page() || is_single() || is_page()) {
?>
<script>
document.addEventListener('DOMContentLoaded', function() {
// Function to toggle Read More / Read Less text
function toggleReadMore(button) {
const container = button.closest('.readmore-less-div'); // Get the closest .readmore-less-div
const description = container.querySelector('.elementor-widget-text-editor .elementor-widget-container p');
// Ensure the description is found before trying to toggle
if (description) {
// Toggle the expanded class
description.classList.toggle('expanded');
// Change the button text based on the state
if (description.classList.contains('expanded')) {
button.textContent = 'Read Less'; // Change button text to "Read Less"
} else {
button.textContent = 'Read More'; // Change button text to "Read More"
}
}
}
// Initially show only the first 25 characters of the description inside .readmore-less-div
const containers = document.querySelectorAll('.readmore-less-div'); // Target only .readmore-less-div containers
containers.forEach(container => {
const description = container.querySelector('.elementor-widget-text-editor .elementor-widget-container p');
if (description) {
const initialText = description.textContent.trim();
const truncatedText = initialText.substring(0, 25) + '...';
// Set the description to the truncated text initially
description.textContent = truncatedText;
// Add click event listener to the Read More button
const readMoreBtn = container.querySelector('.readmorebtn a');
if (readMoreBtn) {
readMoreBtn.addEventListener('click', function(e) {
e.preventDefault(); // Prevent any default action
toggleReadMore(readMoreBtn); // Toggle the expanded class and button text
});
}
}
});
});
</script>
<?php
}
}
add_action('wp_footer', 'custom_readmore_script');
### Explanation of the Changes:
1. **Text Truncation**:
– Initially, we truncate the text in the `description` element to 25 characters and append `…`.
– When the "Read More" button is clicked, the `expanded` class is added to the `description` element, and the full content is shown by removing the truncation (`max-height: none;` and `white-space: normal;`).
2. **Toggling Button Text**:
– After toggling the `expanded` class, we check if the `description` element has the `expanded` class.
– If it has the class, change the button text to "Read Less".
– If it doesn't have the class, change the button text back to "Read More".
3. **CSS**:
– The `read-more-description` class initially limits the text using `max-height` and `white-space: nowrap`.
– The `expanded` class removes these limitations, showing the full content.
### Debugging Tips:
1. **Make sure the `description` element is selected**: If you're seeing that nothing happens when you click the "Read More" button, check the browser console (F12) for any errors. Ensure that the element is found (`description` is not `null`).
To verify, you can add a `console.log(description)` in the `toggleReadMore` function.
2. **Ensure that the `expanded` class is being toggled**: Check if the `expanded` class is being added/removed in the browser’s Developer Tools. Right-click on the description text, inspect it, and verify if the `expanded` class appears when the button is clicked.
3. **Text is not changing**: If the button text isn't changing, ensure the `button.textContent` is correctly updated inside the `toggleReadMore` function. If there are multiple buttons or elements with similar classes, make sure you're targeting the right button.
This updated code should handle both issues. Let me know if you run into any other issues or need further refinements!
### 1. **Ensure the Description Text is Being Truncated Initially**
The first thing to check is whether the description text is being truncated properly on page load.
### 2. **Ensure the Full Text is Being Displayed After "Read More" Click**
When the "Read More" button is clicked, we need to ensure that the class `.expanded` is toggled, and the full text is revealed.
Let's revise the code to ensure everything is set up correctly.
—
### Updated Approach
#### **CSS**: Ensure proper truncation and expansion behavior.
.read-more-description {
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-height: 50px; /* Truncated height */
transition: all 0.3s ease; /* Smooth transition for expanding */
}
/* Expanded text will show fully */
.read-more-description.expanded {
white-space: normal; /* Allow text to wrap */
overflow: visible; /* Show the full content */
max-height: none; /* No height limit when expanded */
}
This CSS ensures:
– **Before expanding**: The `.read-more-description` is truncated to 50px (or whatever you prefer).
– **After expanding**: The `.expanded` class removes the `max-height`, allowing the full content to be shown.
—
#### **JavaScript**: Fix toggling of the text content and handling the expansion.
Here is the updated JavaScript code with a clearer structure:
“`php
function custom_readmore_script() {
// Ensure the script is added only to the frontend
if (is_front_page() || is_single() || is_page()) {
?>
document.addEventListener('DOMContentLoaded', function() {
// Function to toggle Read More / Read Less text
function toggleReadMore(button) {
const container = button.closest('.readmore-less-div'); // Get the closest .readmore-less-div
const description = container.querySelector('.elementor-widget-text-editor .elementor-widget-container p');
if (description) {
// Toggle the expanded class on the description
description.classList.toggle('expanded');
// Change the button text based on the expanded state
if (description.classList.contains('expanded')) {
button.textContent = 'Read Less'; // Change button text to "Read Less"
} else {
button.textContent = 'Read More'; // Change button text back to "Read More"
}
}
}
// Initial text truncation: only show first 25 characters + ellipsis
const containers = document.querySelectorAll('.readmore-less-div'); // Target only .readmore-less-div containers
containers.forEach(container => {
const description = container.querySelector('.elementor-widget-text-editor .elementor-widget-container p');
if (description) {
const initialText = description.textContent.trim();
const truncatedText = initialText.substring(0, 25) + '…';
// Set the description to the truncated text initially
description.textContent = truncatedText;
// Add click event listener to the Read More button
const readMoreBtn = container.querySelector('.readmorebtn a
Let’s walk through a more detailed check to fix this:
### Steps to Ensure the Full Text Displays
1. **CSS for Truncated and Expanded States**
We need to ensure the text is truncated initially, and that when the `expanded` class is toggled, it properly reveals the full text.
2. **JavaScript Logic to Toggle the Text**
Ensure that the JavaScript correctly toggles between the truncated and full text, and changes the button text as well.
### 1. **CSS: Truncating and Expanding Text**
The CSS should define two states:
– **Truncated state**: Initially, we will limit the text and apply `ellipsis` for overflow.
– **Expanded state**: When the text is expanded, we should show the full content.
Here’s an updated CSS that will properly handle the truncation and expansion:
/* Initially truncated text */
.read-more-description {
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-height: 50px; /* Limit height for truncation */
transition: max-height 0.3s ease; /* Smooth transition */
}
/* When the description is expanded */
.read-more-description.expanded {
white-space: normal; /* Allow text to wrap */
overflow: visible; /* Show the full content */
max-height: none; /* No height limit */
}
### 2. **JavaScript: Toggling the Text**
We need to make sure that:
– The initial truncated text is set.
– Clicking "Read More" will reveal the full text.
– The button text should toggle between "Read More" and "Read Less."
### Updated JavaScript Code:
function custom_readmore_script() {
if (is_front_page() || is_single() || is_page()) {
?>
<script>
document.addEventListener('DOMContentLoaded', function() {
// Function to toggle Read More / Read Less text
function toggleReadMore(button) {
const container = button.closest('.readmore-less-div'); // Get the closest .readmore-less-div
const description = container.querySelector('.elementor-widget-text-editor .elementor-widget-container p');
// Ensure the description is found before trying to toggle
if (description) {
// Toggle the expanded class to show/hide the full text
description.classList.toggle('expanded');
// Toggle the button text between "Read More" and "Read Less"
if (description.classList.contains('expanded')) {
button.textContent = 'Read Less'; // Change button text to "Read Less"
} else {
button.textContent = 'Read More'; // Change button text to "Read More"
}
}
}
// Initially show only the first 25 characters of the description inside .readmore-less-div
const containers = document.querySelectorAll('.readmore-less-div'); // Target only .readmore-less-div containers
containers.forEach(container => {
const description = container.querySelector('.elementor-widget-text-editor .elementor-widget-container p');
if (description) {
const initialText = description.textContent.trim();
const truncatedText = initialText.substring(0, 25) + '...';
// Set the description to the truncated text initially
description.textContent = truncatedText;
// Add click event listener to the Read More button
const readMoreBtn = container.querySelector('.readmorebtn a');
if (readMoreBtn) {
readMoreBtn.addEventListener('click', function(e) {
e.preventDefault(); // Prevent any default action
toggleReadMore(readMoreBtn); // Toggle the expanded class and button text
});
}
}
});
});
</script>
<?php
}
}
add_action('wp_footer', 'custom_readmore_script');
### Key Changes:
– **JavaScript (`toggleReadMore` function)**:
– The `description.classList.toggle('expanded')` is used to toggle between truncated and full text.
– The button text is toggled between "Read More" and "Read Less" based on whether the `expanded` class is present on the `description`.
– **CSS**:
– `.read-more-description` has `max-height: 50px` for truncation, and the `expanded` class removes the `max-height` to show the full content.
### Debugging Steps:
1. **Inspect the Text**:
– Right-click the description text in the browser, select "Inspect", and check the class list on the “ element. When you click "Read More", the `expanded` class should be added.
2. **Console Logs**:
– Add `console.log(description)` inside the `toggleReadMore` function to ensure the correct element is being targeted.
### Example Workflow:
1. **Initially**, only the first 25 characters will be visible, followed by "Read More".
2. When you click "Read More", the full description will be shown, and the button text will change to "Read Less".
3. Clicking "Read Less" will truncate the text back to the original 25 characters, and the button will revert to "Read More".
### CSS Transition Example:
If you'd like a smooth transition for showing the full text, you can further modify the CSS:
.read-more-description {
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-height: 50px; /* Truncated height */
transition: max-height 0.3s ease, padding-bottom 0.3s ease; /* Smooth transition for height */
}
.read-more-description.expanded {
white-space: normal; /* Allow text to wrap */
overflow: visible;
max-height: none; /* No height limit */
padding-bottom: 10px; /* Optional padding for visual effect */
}
This ensures that the content expands smoothly when you click "Read More" or "Read Less."
—
With this setup, your "Read More" functionality should now correctly toggle between truncating and showing the full text, and the button text should update as expected. Let me know if you're still having issues or need further assistance!
### Key Points to Address:
1. **Ensure the `expanded` class is properly toggling** the text expansion.
2. **Ensure the CSS properly handles truncation and expansion** by adjusting the `max-height` and `white-space` properties.
3. **Make sure the transition is smooth** for both the height and text wrapping.
### Full Solution: Updated CSS + JavaScript
#### **1. Updated CSS:**
We will tweak the CSS to ensure smooth transition and proper expansion of the text. We'll also ensure the `max-height` and `overflow` are correctly set for truncation and expansion.
/* Initial truncated state */
.read-more-description {
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap; /* Prevent text wrapping */
max-height: 50px; /* Limit height for truncation */
transition: max-height 0.5s ease, padding-bottom 0.3s ease, white-space 0.3s ease; /* Smooth transition */
}
/* Expanded state when the Read More button is clicked */
.read-more-description.expanded {
white-space: normal; /* Allow text to wrap */
overflow: visible; /* Show full content */
max-height: none; /* Remove height limit */
padding-bottom: 10px; /* Optional: Adds padding when expanded */
}
#### **2. JavaScript (Updated):**
We will adjust the JavaScript slightly to ensure that the text is fully revealed when the "Read More" button is clicked, and to handle toggling the button text correctly.
Here’s the updated JavaScript:
function custom_readmore_script() {
if (is_front_page() || is_single() || is_page()) {
?>
<script>
document.addEventListener('DOMContentLoaded', function() {
// Function to toggle Read More / Read Less text
function toggleReadMore(button) {
const container = button.closest('.readmore-less-div'); // Get the closest .readmore-less-div
const description = container.querySelector('.elementor-widget-text-editor .elementor-widget-container p');
// Ensure the description is found before trying to toggle
if (description) {
// Toggle the expanded class to show/hide the full text
description.classList.toggle('expanded');
// Toggle the button text between "Read More" and "Read Less"
if (description.classList.contains('expanded')) {
button.textContent = 'Read Less'; // Change button text to "Read Less"
} else {
button.textContent = 'Read More'; // Change button text to "Read More"
}
}
}
// Initially show only the first 25 characters of the description inside .readmore-less-div
const containers = document.querySelectorAll('.readmore-less-div'); // Target only .readmore-less-div containers
containers.forEach(container => {
const description = container.querySelector('.elementor-widget-text-editor .elementor-widget-container p');
if (description) {
const initialText = description.textContent.trim();
const truncatedText = initialText.substring(0, 25) + '...';
// Set the description to the truncated text initially
description.textContent = truncatedText;
// Add click event listener to the Read More button
const readMoreBtn = container.querySelector('.readmorebtn a');
if (readMoreBtn) {
readMoreBtn.addEventListener('click', function(e) {
e.preventDefault(); // Prevent any default action
toggleReadMore(readMoreBtn); // Toggle the expanded class and button text
});
}
}
});
});
</script>
<?php
}
}
add_action('wp_footer', 'custom_readmore_script');
### Explanation of Changes:
1. **CSS (`max-height` and `white-space`)**:
– The initial `.read-more-description` class limits the height using `max-height: 50px` and prevents wrapping using `white-space: nowrap` to show only a portion of the text.
– When the `.expanded` class is added, it removes the `max-height`, allows the text to wrap (`white-space: normal`), and ensures all content is visible with `overflow: visible`.
2. **JavaScript (`toggleReadMore` function)**:
– The function now toggles the `expanded` class on the description element. If the class is added, it will expand the text; if removed, it will truncate the text again.
– The button text is toggled between "Read More" and "Read Less".
### Debugging:
If the full text still doesn’t show after these changes, try the following:
1. **Check if the `expanded` class is toggling**: Open your browser's Developer Tools (`F12`), go to the "Elements" tab, and inspect the “ element with the class `.read-more-description`. When you click "Read More", check if the `expanded` class is being added to or removed from the element.
2. **Console Logs**: Add a `console.log(description)` inside the `toggleReadMore` function to check if the correct element is being selected.
### Example of How It Should Work:
1. **Initially**:
– Only the first 25 characters of the description are shown.
– The "Read More" button is displayed.
2. **When "Read More" is clicked**:
– The text expands to show the full content.
– The button text changes to "Read Less".
3. **When "Read Less" is clicked**:
– The text is truncated back to the initial 25 characters.
– The button text changes back to "Read More".
With these updates, the "Read More" button should work as expected. If you're still encountering issues, feel free to provide more details, and I'll assist further!
### Updated Solution for Multiple Text Sections
#### **1. CSS:**
The CSS will remain the same for managing truncation and expansion of the text, as it doesn't change based on the number of text elements inside the `.readmore-less-div`.
#### **2. Updated JavaScript:**
Here, we will loop through each `.readmore-less-div` and ensure that:
– Only the relevant text section is truncated or expanded.
– The correct "Read More" button text is toggled for each container.
### JavaScript Code:
function custom_readmore_script() {
if (is_front_page() || is_single() || is_page()) {
?>
<script>
document.addEventListener('DOMContentLoaded', function() {
// Function to toggle Read More / Read Less text
function toggleReadMore(button) {
const container = button.closest('.readmore-less-div'); // Get the closest .readmore-less-div
const descriptions = container.querySelectorAll('.elementor-widget-text-editor .elementor-widget-container p'); // Get all text paragraphs inside the container
// Loop through each description and toggle the expanded class
descriptions.forEach(description => {
// Toggle the expanded class to show/hide the full text
description.classList.toggle('expanded');
});
// Toggle the button text between "Read More" and "Read Less"
if (descriptions[0].classList.contains('expanded')) {
button.textContent = 'Read Less'; // Change button text to "Read Less"
} else {
button.textContent = 'Read More'; // Change button text to "Read More"
}
}
// Initially show only the first 25 characters of the description inside .readmore-less-div
const containers = document.querySelectorAll('.readmore-less-div'); // Target only .readmore-less-div containers
containers.forEach(container => {
const descriptions = container.querySelectorAll('.elementor-widget-text-editor .elementor-widget-container p'); // Get all paragraphs
descriptions.forEach(description => {
const initialText = description.textContent.trim();
const truncatedText = initialText.substring(0, 25) + '...';
// Set the description to the truncated text initially
description.textContent = truncatedText;
});
// Add click event listener to the Read More button
const readMoreBtn = container.querySelector('.readmorebtn a');
if (readMoreBtn) {
readMoreBtn.addEventListener('click', function(e) {
e.preventDefault(); // Prevent any default action
toggleReadMore(readMoreBtn); // Toggle the expanded class and button text
});
}
});
});
</script>
<?php
}
}
add_action('wp_footer', 'custom_readmore_script');
### Explanation of Changes:
1. **Looping through all paragraphs**:
– The `descriptions` variable is now a NodeList that contains all paragraphs (“) within the `.readmore-less-div`.
– We loop through each paragraph and apply the truncation logic (showing only the first 25 characters).
2. **Toggling the `expanded` class**:
– For each paragraph inside `.readmore-less-div`, we toggle the `expanded` class to expand or collapse the text.
– This ensures that multiple text blocks can each be toggled independently.
3. **Button Text Toggle**:
– We check the first description (`descriptions[0]`) to determine whether the `expanded` class is active.
– If any description inside the container is expanded, we change the button text to "Read Less". If no descriptions are expanded, the button text is changed back to "Read More".
### Notes:
– **Handling Multiple Text Blocks**: The code is now set up to work with multiple “ tags inside each `.readmore-less-div` container.
– **Event Binding**: The `Read More/Read Less` functionality works independently for each `.readmore-less-div` container, so each section can have its own button and content that expands or collapses.
### Example HTML Structure:
<div class="readmore-less-div">
<div class="elementor-widget-text-editor">
<div class="elementor-widget-container">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed non risus. Suspendisse lectus tortor, dignissim sit amet, adipiscing nec, ultricies sed, dolor.</p>
<p>Additional paragraph that may or may not be truncated.</p>
</div>
</div>
<div class="readmorebtn">
<a href="#">Read More</a>
</div>
</div>
### How It Works:
1. **Initially**, the first 25 characters of the text are displayed.
2. When you click "Read More":
– The text expands (including all paragraphs within that container).
– The button text changes to "Read Less".
3. When you click "Read Less", the text will collapse back to the initial 25 characters.
### Debugging:
– **Check that each `description` is being selected correctly**: If you inspect the element in the browser (F12) and look at the text content, ensure the truncated text is being applied initially.
– **Inspect the `expanded` class**: Use the browser's Developer Tools to inspect the “ elements and see if the `expanded` class is being added or removed properly when you click the "Read More" button.
With this setup, you should now be able to toggle the full text of multiple text blocks inside each `.readmore-less-div`. Let me know if you encounter any further issues!
if (is_front_page() || is_single() || is_page()) {
?>
<script>
document.addEventListener('DOMContentLoaded', function() {
// Function to toggle Read More / Read Less text
function toggleReadMore(button,initialText,shortt) {
const container = button.closest('.readmore-less-div'); // Get the closest .readmore-less-div
const description = container.querySelector('.elementor-widget-text-editor .elementor-widget-container p');
// Ensure the description is found before trying to toggle
if (description) {
// Toggle the expanded class to show/hide the full text
description.classList.toggle('expanded');
// Toggle the button text between "Read More" and "Read Less"
if (description.classList.contains('expanded')) {
button.textContent = 'Read Less'; // Change button text to "Read Less"
description.textContent=initialText;
} else {
button.textContent = 'Read More'; // Change button text to "Read More"
description.textContent=shortt;
}
}
}
// Initially show only the first 25 characters of the description inside .readmore-less-div
const containers = document.querySelectorAll('.readmore-less-div'); // Target only .readmore-less-div containers
containers.forEach(container => {
const description = container.querySelector('.elementor-widget-text-editor .elementor-widget-container p');
alert("dsdsd");
if (description) {
const initialText = description.textContent.trim();
const truncatedText = initialText.substring(0, 75) + '...';
// Set the description to the truncated text initially
description.textContent = truncatedText;
// Add click event listener to the Read More button
const readMoreBtn = container.querySelector('.readmorebtn a');
if (readMoreBtn) {
readMoreBtn.addEventListener('click', function(e) {
alert('dd');
e.preventDefault(); // Prevent any default action
toggleReadMore(readMoreBtn,initialText,truncatedText); // Toggle the expanded class and button text
});
}
}
});
});
</script>
### Updated JavaScript Solution:
In this case, we need to iterate over each `.read-more-card` inside `.readmore-less-div` and manage the "Read More" / "Read Less" functionality independently for each one.
Here's the updated JavaScript code that should work with multiple `.read-more-card` elements inside `.readmore-less-div`.
### Updated Code:
function custom_readmore_script() {
if (is_front_page() || is_single() || is_page()) {
?>
<script>
document.addEventListener('DOMContentLoaded', function() {
// Function to toggle Read More / Read Less text
function toggleReadMore(button, initialText, truncatedText) {
const container = button.closest('.readmore-less-div'); // Get the closest .readmore-less-div
const card = button.closest('.read-more-card'); // Get the closest .read-more-card within the container
const description = card.querySelector('.elementor-widget-text-editor .elementor-widget-container p'); // Find the paragraph inside the card
if (description) {
// Toggle the expanded class to show/hide the full text
description.classList.toggle('expanded');
// Toggle the button text between "Read More" and "Read Less"
if (description.classList.contains('expanded')) {
button.textContent = 'Read Less'; // Change button text to "Read Less"
description.textContent = initialText; // Show the full text
} else {
button.textContent = 'Read More'; // Change button text to "Read More"
description.textContent = truncatedText; // Show the truncated text
}
}
}
// Initially show only the first 75 characters of the description inside each .read-more-card
const containers = document.querySelectorAll('.readmore-less-div'); // Target only .readmore-less-div containers
containers.forEach(container => {
const cards = container.querySelectorAll('.read-more-card'); // Get all .read-more-card elements within the container
cards.forEach(card => {
const description = card.querySelector('.elementor-widget-text-editor .elementor-widget-container p'); // Get the paragraph inside the card
if (description) {
const initialText = description.textContent.trim(); // Get the full text
const truncatedText = initialText.substring(0, 75) + '...'; // Truncate to the first 75 characters
// Set the description to the truncated text initially
description.textContent = truncatedText;
// Add click event listener to the Read More button
const readMoreBtn = card.querySelector('.readmorebtn a'); // Find the Read More button in the card
if (readMoreBtn) {
readMoreBtn.addEventListener('click', function(e) {
e.preventDefault(); // Prevent any default action (e.g., navigation)
toggleReadMore(readMoreBtn, initialText, truncatedText); // Toggle the expanded text and button
});
}
}
});
});
});
</script>
<?php
}
}
add_action('wp_footer', 'custom_readmore_script');
### Explanation of Changes:
1. **Targeting `.read-more-card` inside `.readmore-less-div`**:
– We now loop through all `.read-more-card` elements inside each `.readmore-less-div` container.
– For each `.read-more-card`, we grab the text content inside its respective “ tag and apply the "Read More" functionality individually.
2. **Handling Multiple Cards**:
– The `toggleReadMore` function now works for individual cards. It checks the text inside the specific card and toggles it between truncated and expanded states.
3. **Button Text Toggle**:
– When the "Read More" button is clicked, the text of the button changes accordingly to either "Read More" or "Read Less" based on the expanded state of the description.
4. **Initial Text**:
– The full text (`initialText`) and truncated text (`truncatedText`) are passed to the `toggleReadMore` function, ensuring the correct state is toggled each time.
### Example HTML Structure:
<div class="readmore-less-div">
<div class="read-more-card">
<div class="elementor-widget-text-editor">
<div class="elementor-widget-container">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed non risus. Suspendisse lectus tortor, dignissim sit amet, adipiscing nec, ultricies sed, dolor.</p>
</div>
</div>
<div class="readmorebtn">
<a href="#">Read More</a>
</div>
</div>
<div class="read-more-card">
<div class="elementor-widget-text-editor">
<div class="elementor-widget-container">
<p>Another card with more content. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam tincidunt.</p>
</div>
</div>
<div class="readmorebtn">
<a href="#">Read More</a>
</div>
</div>
</div>
### How It Works:
1. **Initially**, each `.read-more-card` will show only the first 75 characters of its paragraph content.
2. When the "Read More" button is clicked:
– The text expands to show the full content for that particular card.
– The button text changes to "Read Less".
3. When "Read Less" is clicked:
– The text is truncated again, showing only the first 75 characters.
– The button text changes back to "Read More".
### Debugging:
– **Console Logs**: If the functionality isn't working as expected, you can add `console.log()` inside the `toggleReadMore` function to check if the text content is correctly being set and if the event listener is firing correctly.
Example:
console.log('Toggling text:', description.textContent);
Let me know if this works for you or if you encounter any issues!
### Key Changes:
1. **Truncate Text to 75 Characters**: The text will initially show only the first 75 characters.
2. **Add Ellipsis (`…`)**: If the text exceeds 75 characters, it will show "…" at the end.
### Updated JavaScript:
function custom_readmore_script() {
if (is_front_page() || is_single() || is_page()) {
?>
<script>
document.addEventListener('DOMContentLoaded', function() {
// Function to toggle Read More / Read Less text
function toggleReadMore(button, initialText, truncatedText) {
const container = button.closest('.readmore-less-div'); // Get the closest .readmore-less-div
const card = button.closest('.read-more-card'); // Get the closest .read-more-card within the container
const description = card.querySelector('.elementor-widget-text-editor .elementor-widget-container p'); // Find the paragraph inside the card
if (description) {
// Toggle the expanded class to show/hide the full text
description.classList.toggle('expanded');
// Toggle the button text between "Read More" and "Read Less"
if (description.classList.contains('expanded')) {
button.textContent = 'Read Less'; // Change button text to "Read Less"
description.textContent = initialText; // Show the full text
} else {
button.textContent = 'Read More'; // Change button text to "Read More"
description.textContent = truncatedText; // Show the truncated text
}
}
}
// Initially show only the first 75 characters of the description inside each .read-more-card
const containers = document.querySelectorAll('.readmore-less-div'); // Target only .readmore-less-div containers
containers.forEach(container => {
const cards = container.querySelectorAll('.read-more-card'); // Get all .read-more-card elements within the container
cards.forEach(card => {
const description = card.querySelector('.elementor-widget-text-editor .elementor-widget-container p'); // Get the paragraph inside the card
if (description) {
const initialText = description.textContent.trim(); // Get the full text
const truncatedText = initialText.length > 75 ? initialText.substring(0, 75) + '...' : initialText; // Truncate to the first 75 characters with ellipsis if necessary
// Set the description to the truncated text initially
description.textContent = truncatedText;
// Add click event listener to the Read More button
const readMoreBtn = card.querySelector('.readmorebtn a'); // Find the Read More button in the card
if (readMoreBtn) {
readMoreBtn.addEventListener('click', function(e) {
e.preventDefault(); // Prevent any default action (e.g., navigation)
toggleReadMore(readMoreBtn, initialText, truncatedText); // Toggle the expanded text and button
});
}
}
});
});
});
</script>
<?php
}
}
add_action('wp_footer', 'custom_readmore_script');
### Key Adjustments:
– **Truncating Text**:
– The `truncatedText` is now calculated by checking if the content length exceeds 75 characters. If it does, we truncate it to the first 75 characters and add `"…"` at the end. If the text is already 75 characters or fewer, no truncation happens.
const truncatedText = initialText.length > 75 ? initialText.substring(0, 75) + '...' : initialText;
– **Full Text and Truncated Text**:
– When the button is clicked, we toggle between the full `initialText` and the truncated `truncatedText`.
### Example HTML Structure (for reference):
<div class="readmore-less-div">
<div class="read-more-card">
<div class="elementor-widget-text-editor">
<div class="elementor-widget-container">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed non risus. Suspendisse lectus tortor, dignissim sit amet, adipiscing nec, ultricies sed, dolor.</p>
</div>
</div>
<div class="readmorebtn">
<a href="#">Read More</a>
</div>
</div>
<div class="read-more-card">
<div class="elementor-widget-text-editor">
<div class="elementor-widget-container">
<p>Another card with more content. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam tincidunt.</p>
</div>
</div>
<div class="readmorebtn">
<a href="#">Read More</a>
</div>
</div>
</div>
### How It Works:
1. **Initially**, the first 75 characters of the text inside each `.read-more-card` will be displayed.
– If the text exceeds 75 characters, it will show "…" at the end.
2. When you click "Read More", the full content of the text is revealed and the button text changes to "Read Less".
3. When you click "Read Less", the content is truncated back to 75 characters, and the button text changes back to "Read More".
### Debugging:
If you notice that the truncation is not working as expected, inspect the HTML in your browser's Developer Tools (F12) and check the content inside the “ tags to see if the truncated text is being correctly set. You can also add `console.log` statements in the JavaScript to debug the initial and truncated text.
Example:
console.log('Initial Text:', initialText);
console.log('Truncated Text:', truncatedText);
This setup should ensure that the text is correctly truncated to 75 characters and behaves as expected when toggling between "Read More" and "Read Less". Let me know if you encounter any issues!