Posted on

Scroll result page to the search term

Relevanssi can highlight search terms on the posts. But how about scrolling the page to show the location where the search results are? That is also possible.

It requires a bit of JavaScript on the post page.

This script needs to run on the post page:

<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("highlight");
	var offsetToWord = $("p:containsNC('" +mySearchString + "'):first").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>

The easiest way is to just add this to the single post template, but the right way is to use wp_enqueue_script(). Now the post page will automatically scroll to the location of the search term, taken from the “highlight” query parameter. The scroll is instant; if you want to make it slower, increase the 0 in $("html, body").animate({ scrollTop: offsetToWord }, 0); to 1000 or 2000 to get a slower animation.

Now all you need is the search term in the highlight parameter. On your search results template, you likely have something like this:

<a href="<?php the_permalink(); ?>"><!--?php _e( 'Read More', 'total' ); ?--></a>

Change it to this to append the search query to the URL:

<a href="<?php if (function_exists('relevanssi_the_permalink')) { relevanssi_the_permalink(); } else { the_permalink(); } ?>"><!--?php _e( 'Read More', 'total' ); ?--></a>

This is a fairly brutal method and probably lacks all sorts of necessary finesse, but it’s a start. Note that this only works when the whole search query is found somewhere on the page; it looks for the whole phrase, not individual words.

Another method

For a simpler and more reliable approach, make sure the in-document highlighting is enabled and set it to use something distinct, like that <mark> tag or a specific CSS classname. Then you can use this script to jump to the first occurrance of the highlighting:

<script>
jQuery(document).ready(function($) {
    var offset = $('mark').first().offset().top // for <mark> tags
    var offset = $('.classname').first().offset().top // for CSS class name
    $("html, body").animate({ scrollTop: offset }, 100);
})
</script>

11 comments Scroll result page to the search term

  1. Search to return EXCERPTS – Genesis Outreach Pro.

    There is no access to a search.php in the backend of Outreach pro.
    I am not a developer but have dappled successfully with my functions PHP – shortcodes, etc.

    My problem is that I cannot find where to add the excerpts() command, to force my searches to return a predetermined number of lines from relevant pages. ATM, I am getting impossibly full page dumps. I tried functions.php but to no avail.
    Could somebody please advise where and what code I should be adding to enable Relevanssi to return excerpts of pages. I have few posts; my site is almost entirely comprised of pages.

    Much appreciated.
    Martin Cooper

      1. It worked! Your response time was exceptional, Mikko.

        I am extremely impressed.

        Cheers from Australia.

  2. I’m using divi and relevanssi does an amazing job of show the relevant content in the search results excerpts. I do want it to scroll to that content when i click the results, and your post seems to be the only solution to do the same but which page template or page do i have to edit to make this happen. I’m a little lost as to how to achieve this?

    1. Renee, if you’re lost with this, I would recommend hiring a WP developer to implement this for you. Getting this work is going to require WordPress developer expertise.

      1. Hello Mikko.

        Thank you for the wonderful work. Relevanssi is indeed an amazing search plugin. It does exactly what its name says.

        My little challenge with the plugin is the same with that raised by Renee. I seriously want the plugin to scroll from the result page to the location where the search keyword is first found, at a click.

        I have engaged freelancers on Fiverr but none is able to achieve this. I truly need your assistance to achieve this.

        Thank you

  3. Hello Mikko, your post is the only solution to my problem, i installed and activated relevansi, set the highlight to mark , and tried adding these codes you mentioned but nothing seems to work, the search still doesnt scroll to the search term i wanted in the page , i am using Mestc theme from themeforest .
    can u please guide me how to solve it .
    thank you in advance !

Leave a Reply

Are you a Relevanssi Premium customer looking for support? Please use the Premium support form.

Your email address will not be published. Required fields are marked *