Certainly! Based on your existing code and requirements, I'll help you implement the JavaScript logic for displaying the loaded text with pagination, where each word is clickable and triggers the updateBubble(event) function. Below, I'll provide the necessary JavaScript code and explain how it integrates with your existing functions. I'll also show you the HTML structure where the text will be injected.
1. HTML Structure
First, ensure you have an HTML container where the text will be displayed. We'll use a <div> element with the ID text-display for this purpose. Additionally, we'll add pagination controls.
<!-- Container for displaying the text -->
<div id="text-display"></div>
<!-- Pagination Controls -->
<div id="pagination-controls">
<button id="prevPageBtn" onclick="prevTextPage()">Previous</button>
<span id="currentPageIndicator">Page 1</span>
<button id="nextPageBtn" onclick="nextTextPage()">Next</button>
</div>
2. JavaScript Logic
Global Variables
We'll need some global variables to manage pagination and the text content.
let currentText = ""; // Holds the full text content
let currentTextPages = []; // Array to hold text split into pages
let currentTextPageIndex = 0; // Index of the current page being displayed
const wordsPerPage = 500; // Adjust this value as needed
Function to Fetch and Load Text
We'll modify your existing fetchAndLoadText function to fetch the text content from the server, split it into pages, and display the first page.
function fetchAndLoadText(textName) {
selectedWords = [];
wordCount = {};
// Remove highlighting from previously active item
const previousActiveItem = document.querySelector('.list-group-item.active-text');
if (previousActiveItem) {
previousActiveItem.classList.remove('active-text');
}
// Find the clicked list item based on the text name and add highlight class
const activeItem = document.querySelector(`li[data-name="${textName}"]`);
if (activeItem) {
activeItem.classList.add('active-text');
}
if (actionBubble != null) {
document.body.removeChild(actionBubble);
actionBubble = null;
}
// Fetch the text content from the server
fetch(`/user/get_text_content?name=${encodeURIComponent(textName)}`)
.then(response => response.text())
.then(text => {
currentText = text;
currentTextPages = splitTextIntoPages(currentText, wordsPerPage);
currentTextPageIndex = 0;
displayCurrentTextPage();
updatePageIndicator();
})
.catch(error => {
console.error('Error fetching text content:', error);
showAlert('Error fetching text content.', 'danger');
});
}
Explanation:
- We fetch the full text content from the server using a GET request.
- Once the text is received, we store it in
currentText.
- We split the text into pages using the
splitTextIntoPages function.
- We reset the page index to
0 and display the first page using displayCurrentTextPage().
updatePageIndicator() updates the pagination controls.
Function to Split Text into Pages
function splitTextIntoPages(text, wordsPerPage) {
const words = text.split(/\s+/);
const pages = [];
for (let i = 0; i < words.length; i += wordsPerPage) {
const pageWords = words.slice(i, i + wordsPerPage);
pages.push(pageWords.join(' '));
}
return pages;
}
Explanation:
- This function splits the text into an array of pages, each containing
wordsPerPage words.
- Adjust
wordsPerPage as needed to fit your application's requirements.
Function to Display the Current Text Page
function displayCurrentTextPage() {
const textDisplay = document.getElementById('text-display');
textDisplay.innerHTML = ''; // Clear existing content
if (currentTextPages.length === 0) {
textDisplay.innerText = 'No content to display.';
return;
}
const pageContent = currentTextPages[currentTextPageIndex];
const words = pageContent.split(/\s+/);
words.forEach((word, index) => {
const wordSpan = document.createElement('span');
wordSpan.innerText = word;
wordSpan.className = 'text-word';
wordSpan.addEventListener('click', (event) => {
selectWord(event, wordSpan, index);
updateBubble(event);
});
textDisplay.appendChild(wordSpan);
textDisplay.appendChild(document.createTextNode(' ')); // Add space between words
});
}
Explanation:
- Clears the
text-display container.
- Retrieves the current page content.
- Splits the page content into individual words.
- Creates a
<span> for each word, making it clickable.
- Adds an event listener to each word to handle selection and bubble activation.
- Appends each word to the
text-display container, adding spaces as needed.
Function to Handle Word Selection
function selectWord(event, wordElement, wordIndex) {
// Handle word selection logic here
// For example, toggle 'selected' class
if (wordElement.classList.contains('selected')) {
wordElement.classList.remove('selected');
const index = selectedWords.indexOf(wordIndex);
if (index > -1) {
selectedWords.splice(index, 1);
}
} else {
wordElement.classList.add('selected');
selectedWords.push(wordIndex);
}
}
Explanation:
- Toggles whether a word is selected.
- Updates the
selectedWords array accordingly.
Pagination Control Functions
function nextTextPage() {
if (currentTextPageIndex < currentTextPages.length - 1) {
currentTextPageIndex++;
displayCurrentTextPage();
updatePageIndicator();
if (actionBubble != null) {
document.body.removeChild(actionBubble);
actionBubble = null;
}
}
}
function prevTextPage() {
if (currentTextPageIndex > 0) {
currentTextPageIndex--;
displayCurrentTextPage();
updatePageIndicator();
if (actionBubble != null) {
document.body.removeChild(actionBubble);
actionBubble = null;
}
}
}
function updatePageIndicator() {
const pageIndicator = document.getElementById('currentPageIndicator');
pageIndicator.innerText = `Page ${currentTextPageIndex + 1} of ${currentTextPages.length}`;
const nextPageBtn = document.getElementById('nextPageBtn');
const prevPageBtn = document.getElementById('prevPageBtn');
nextPageBtn.disabled = currentTextPageIndex >= currentTextPages.length - 1;
prevPageBtn.disabled = currentTextPageIndex <= 0;
}
Explanation:
nextTextPage() and prevTextPage() navigate between pages.
updatePageIndicator() updates the pagination display and enables/disables buttons as needed.
- We also remove the
actionBubble when changing pages to prevent it from persisting.
3. CSS Styling (Optional)
For better visual representation, you might want to add some CSS:
/* Style for text words */
.text-word {
cursor: pointer;
}
/* Highlight selected words */
.text-word.selected {
background-color: yellow;
}
/* Pagination controls */
#pagination-controls {
display: flex;
justify-content: center;
align-items: center;
margin-top: 10px;
}
#pagination-controls button {
margin: 0 10px;
}
4. Full Integration
Now, your code should integrate the pagination and clickable words functionality seamlessly. Here's how the core functions fit together:
fetchAndLoadText(textName): Fetches the text and initializes pagination.
splitTextIntoPages(text, wordsPerPage): Splits the full text into pages.
displayCurrentTextPage(): Displays the current page with clickable words.
selectWord(event, wordElement, wordIndex): Handles word selection logic.
updateBubble(event): Activates the bubble when a word is clicked (implementation assumed to be already provided).
- Pagination controls (
nextTextPage, prevTextPage, and updatePageIndicator) manage page navigation.
5. Example Server Endpoint
Ensure your server has an endpoint to provide the text content. For example:
# Flask example
@app.route('/user/get_text_content')
def get_text_content():
text_name = request.args.get('name')
# Retrieve the text content based on the text_name
# For example, read from a database or file
text_content = ... # Your logic here
return text_content
6. Testing
- Load your page and ensure the list of texts is displayed.
- Click on a text to load it.
- The text should display in the
text-display container, split into pages.
- Each word should be clickable, and clicking a word should trigger the
updateBubble(event) function.
7. Additional Notes
- Performance Considerations: For very large texts, consider implementing lazy loading or rendering only the visible portion of the page to improve performance.
- Responsive Design: Ensure that your CSS styles allow for a responsive design, especially if users will access the application on mobile devices.
- Error Handling: Add additional error handling as needed, for example, if the text content fails to load.
8. Putting It All Together
Here's the combined JavaScript code with the necessary functions:
// Global Variables
let currentText = "";
let currentTextPages = [];
let currentTextPageIndex = 0;
const wordsPerPage = 500;
let selectedWords = [];
let wordCount = "";
// ... Your existing variables and code ...
// Function to fetch and load text
function fetchAndLoadText(textName) {
selectedWords = [];
wordCount = {};
// Remove highlighting from previously active item
const previousActiveItem = document.querySelector('.list-group-item.active-text');
if (previousActiveItem) {
previousActiveItem.classList.remove('active-text');
}
// Find the clicked list item based on the text name and add highlight class
const activeItem = document.querySelector(`li[data-name="${textName}"]`);
if (activeItem) {
activeItem.classList.add('active-text');
}
if (actionBubble != null) {
document.body.removeChild(actionBubble);
actionBubble = null;
}
// Fetch the text content from the server
fetch(`/user/get_text_content?name=${encodeURIComponent(textName)}`)
.then(response => response.text())
.then(text => {
currentText = text;
currentTextPages = splitTextIntoPages(currentText, wordsPerPage);
currentTextPageIndex = 0;
displayCurrentTextPage();
updatePageIndicator();
})
.catch(error => {
console.error('Error fetching text content:', error);
showAlert('Error fetching text content.', 'danger');
});
}
// Function to split text into pages
function splitTextIntoPages(text, wordsPerPage) {
const words = text.split(/\s+/);
const pages = [];
for (let i = 0; i < words.length; i += wordsPerPage) {
const pageWords = words.slice(i, i + wordsPerPage);
pages.push(pageWords.join(' '));
}
return pages;
}
// Function to display the current text page
function displayCurrentTextPage() {
const textDisplay = document.getElementById('text-display');
textDisplay.innerHTML = ''; // Clear existing content
if (currentTextPages.length === 0) {
textDisplay.innerText = 'No content to display.';
return;
}
const pageContent = currentTextPages[currentTextPageIndex];
const words = pageContent.split(/\s+/);
words.forEach((word, index) => {
const wordSpan = document.createElement('span');
wordSpan.innerText = word;
wordSpan.className = 'text-word';
wordSpan.addEventListener('click', (event) => {
selectWord(event, wordSpan, index);
updateBubble(event);
});
textDisplay.appendChild(wordSpan);
textDisplay.appendChild(document.createTextNode(' ')); // Add space between words
});
}
// Function to handle word selection
function selectWord(event, wordElement, wordIndex) {
// Handle word selection logic here
// For example, toggle 'selected' class
if (wordElement.classList.contains('selected')) {
wordElement.classList.remove('selected');
const index = selectedWords.indexOf(wordIndex);
if (index > -1) {
selectedWords.splice(index, 1);
}
} else {
wordElement.classList.add('selected');
selectedWords.push(wordIndex);
}
}
// Pagination control functions
function nextTextPage() {
if (currentTextPageIndex < currentTextPages.length - 1) {
currentTextPageIndex++;
displayCurrentTextPage();
updatePageIndicator();
if (actionBubble != null) {
document.body.removeChild(actionBubble);
actionBubble = null;
}
}
}
function prevTextPage() {
if (currentTextPageIndex > 0) {
currentTextPageIndex--;
displayCurrentTextPage();
updatePageIndicator();
if (actionBubble != null) {
document.body.removeChild(actionBubble);
actionBubble = null;
}
}
}
function updatePageIndicator() {
const pageIndicator = document.getElementById('currentPageIndicator');
pageIndicator.innerText = `Page ${currentTextPageIndex + 1} of ${currentTextPages.length}`;
const nextPageBtn = document.getElementById('nextPageBtn');
const prevPageBtn = document.getElementById('prevPageBtn');
nextPageBtn.disabled = currentTextPageIndex >= currentTextPages.length - 1;
prevPageBtn.disabled = currentTextPageIndex <= 0;
}
// Assume updateBubble(event) is already implemented
// function updateBubble(event) { ... }
// Your existing code continues...
9. Conclusion
By integrating the above JavaScript logic with your existing application, you should be able to display texts with pagination, allowing users to navigate through pages like a book. Each word is made clickable, and clicking on a word triggers the updateBubble(event) function you've already implemented.
Please make sure to test each part thoroughly and adjust any parameters (like wordsPerPage) to fit your specific needs.
Let me know if you need further assistance or have any questions!