• I’ve been trying for some time now to add an auto-scroll upon a search-term on my WordPress without success. The site is allocated on the local server of my workplace (and connects under the domain WORKPLACE.LOCAL, as an example) and I’m using a free plugin (WPCode) to add two functions. The idea us that I search something, like a name on the search bar and then select any of the results I’m given. Then, two things must happen: One, the word I searched needs to be highlighted and second, the page needs to move to the part in which that word is located.

    The first part, the search-term highlight, works flawlessly. I’m using Relevanssi (another free plugin) to define the highlight term as “mark” and create the highlight with the following code:

    mark {
    
    background-color: #6e35ae; /* #4b5980 */
    
    color: yellow;
    
    font-weight: bold;
    
    padding: 0 2px;
    
    border-radius: 3px;
    
    }

    However, when trying to add the auto-scroll function using this code:

    document.addEventListener("DOMContentLoaded", function () {
    
    let hash = window.location.hash;
    
    if (hash.startsWith("#search-")) {
    
    let searchTerm = hash.replace("#search-", "").replace(/-/g, " "); // Convert dashes back to spaces
    
    let regex = new RegExp(searchTerm, "gi");
    
    let paragraphs = document.querySelectorAll("p, h1, h2, h3, h4, h5, h6, span, div");
    
    paragraphs.forEach(el => {
    
    if (el.textContent.match(regex)) {
    
    el.scrollIntoView({ behavior: "instant", block: "center" }); // Jump instantly
    
    el.innerHTML = el.innerHTML.replace(regex, <mark>${searchTerm}</mark>); // Highlight text
    
    return;
    
    }
    
    });
    
    }
    
    });

    Nothing happens.

    The best thing that I manage to do is adding a second scroll-bar that works, but the main one (and the one that covers all the page’s height) is not doing anything.

    I’ve tried a lot with the code in order to make it work but everything has been futile so far… any ideas? Anything will be greatly appreciated.

Viewing 1 replies (of 1 total)
  • Let’s troubleshoot and refine your auto-scroll implementation. The core issue likely involves timingelement 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:

    1. Browser console errors.
    2. A live example URL (if possible).
    3. 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.
Viewing 1 replies (of 1 total)

The topic ‘Cannot Add Auto-Scroll Function’ is closed to new replies.