• Resolved skupke

    (@skupke)


    Hey Guys.

    Is there a way to include a feature like an automatic scrolling/jumping to the search term (on the page where my search term was found) when hitting the button on the search results page?

    Sorry for the bad english.

    Hope that anybody can help.

    Cheers
    Sebastian

Viewing 4 replies - 1 through 4 (of 4 total)
  • Plugin Author Mikko Saari

    (@msaari)

    It’s possible to do, just requires some javascript. Here’s a Stack Overflow page on the question.

    Then it’s just a question of figuring out the search query. Relevanssi does that for highlighting, so you can see how it’s done in relevanssi_highlight_in_docs function in lib/excerpts-highlights.php.

    Then when the page is loaded, just find out the search query and use the javascript code to scroll to it.

    Thread Starter skupke

    (@skupke)

    Hello Mikko, thanks for the hint. I tried a lot but I failed. The Searchquery is in the URL. So I tried to fetch it out of the URL.

    This is my JS:

    function $_GET(param) {
    	var vars = {};
    	window.location.href.replace( location.hash, '' ).replace( 
    		/[?&]+([^=&]+)=?([^&]*)?/gi, // regexp
    		function( m, key, value ) { // callback
    			vars[key] = value !== undefined ? value : '';
    		}
    	);
    	return vars;
    }
    
    var mySearchString = $_GET("hilite");
    
    //my Theme needs a starting jQuery in the Editor
    jQuery(
    function searchscroll(Str) { 
    
    $(window).scrollTop(-80 + $("p:contains(Str):first-child").offset().top);
    alert("test");
    }
    
    searchscroll(mySearchString);
    );
    
    

    Can u help me?

    Plugin Author Mikko Saari

    (@msaari)

    Since I get requests for this every now and then, I took a look at this and ended up with this:

    <script>
    jQuery(document).ready(function($) {
    	$.extend($.expr[":"], {
    		"containsNC": function(elem, i, match, array) {
    			return (elem.textContent || elem.innerText || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
    		}
    	});
    
    	var mySearchString = getParams("hilite");
    	var offsetToWord = $("p:containsNC('" +mySearchString + "'):last").offset().top;
    	
    	$("html, body").animate({ scrollTop: offsetToWord }, 0);
    	
    	function getParams(param) {
    		var vars = {};
    		window.location.href.replace( location.hash, '' ).replace( 
    			/[?&]+([^=&]+)=?([^&]*)?/gi, // regexp
    			function( m, key, value ) { // callback
    				vars[key] = value !== undefined ? value : '';
    			}
    		);
    		return vars[param];
    	}
    });
    </script>

    This seems to work.

    Thread Starter skupke

    (@skupke)

    Awesome! Thank you!

Viewing 4 replies - 1 through 4 (of 4 total)

The topic ‘Scroll to search term’ is closed to new replies.