Let’s troubleshoot and refine your auto-scroll implementation. The core issue likely involves timing, element selection, or scroll behavior conflicts.
Here’s a step-by-step solution:
1. Fix Timing Issues
The DOMContentLoaded event might fire before WordPress or Relevanssi finishes rendering search results. Use a delayed check or observe dynamic content:
javascript
function scrollToSearchTerm() { const hash = window.location.hash; if (hash.startsWith(“#search-“)) { const searchTerm = hash.replace(“#search-“, “”).replace(/-/g, ” “); const regex = new RegExp(\\b${searchTerm}\\b, “gi”); // Match whole words // Wait for Relevanssi highlights (delay execution) setTimeout(() => { // Target highlighted terms directly (Relevanssi adds <mark> tags) const markedElements = document.querySelectorAll(“mark”); if (markedElements.length > 0) { markedElements[0].scrollIntoView({ behavior: “auto”, block: “center”, inline: “nearest” }); } }, 500); // Adjust delay based on page load speed } } // Run on initial load and hash changes window.addEventListener(“load”, scrollToSearchTerm); window.addEventListener(“hashchange”, scrollToSearchTerm);
2. Improve Element Targeting
Instead of iterating through all paragraphs/headings:
- Target Relevanssi’s existing highlights (they already wrap the term in
<mark> tags).
- Use
document.querySelector("mark") to jump to the first highlighted instance.
3. Adjust Scroll Behavior
- Ensure you’re not conflicting with nested scroll containers (e.g., if your theme uses a custom scrollable div).
- Force the main window to scroll instead of a child container:
- javascript
- // Add this if scrolling a parent container document.documentElement.scrollIntoView({ behavior: “auto” });<gwmw style=”display:none;”></gwmw><gwmw style=”display:none;”></gwmw>
4. Debugging Stepsa. Check Console for Errors
- Open the browser console (F12 → Console) to see if JavaScript errors occur when clicking search results.
b. Log Values
Add debug statements to your code:
javascript
console.log(“Search term:”, searchTerm); console.log(“Marked elements found:”, markedElements.length);
c. Test URL Structure<gwmw style=”display:none;”></gwmw>
Ensure the URL hash after a search is formatted correctly (e.g., #search-example-term). Relevanssi or your theme might be overriding this.
5. Alternative Approach: Use Relevanssi Hooks<gwmw style=”display:none;”></gwmw>
Relevanssi has filters for custom behavior. Instead of relying on URL hashes:
php
// Add to functions.php or WPCode Snippet add_action(‘relevanssi_search_results’, ‘custom_scroll_to_highlight’); function custom_scroll_to_highlight($results) { if (!empty($results)) { echo ‘<script> window.location.hash = “search-‘ . urlencode(get_search_query()) . ‘”; </script>’; } return $results; }
6. CSS Fixes
Ensure highlighted <mark> elements are not hidden or styled in a way that breaks scrolling:
css
mark { background-color: #6e35ae; color: yellow; /* Add this to ensure marks are visible/scrollable */ position: relative; z-index: 9999; }
7. Final Code Example
Here’s a consolidated version:
javascript
function scrollToSearchTerm() { const hash = window.location.hash; if (hash.startsWith(“#search-“)) { const searchTerm = hash.replace(“#search-“, “”).replace(/-/g, ” “); // Wait for Relevanssi to highlight terms setTimeout(() => { const markedElements = document.querySelectorAll(“mark”); if (markedElements.length > 0) { markedElements[0].scrollIntoView({ behavior: “auto”, block: “center” }); } else { console.warn(“No highlighted terms found.”); } }, 750); // Increase delay if page loads slowly } } // Initialize window.addEventListener(“load”, scrollToSearchTerm); window.addEventListener(“hashchange”, scrollToSearchTerm);
Key Takeaways:
- Timing: Wait for Relevanssi to finish highlighting terms.
- Targeting: Use
<mark> elements created by Relevanssi instead of reinventing highlighting.
- Debugging: Check for JavaScript errors and ensure the URL hash is properly formatted.
If issues persist, share:
- Browser console errors.
- A live example URL (if possible).
- Whether your theme uses AJAX to load search results (this would require additional handling).
-
This reply was modified 1 year, 2 months ago by
saghir daska.