-1

First, a user searches something. Then, they go to a page that has the keyword highlighted on the document. I want the page to automatically go to the first highlight.

The url looks something like this: page.php?keyword=apple

From this url, I want the first instance of apple to be on the very top of the page when the document is opened. How can this be accomplished?

EDIT

Maybe I was unclear, I do not want to highlight the word. I want to scroll to the position where the word is found. The first instance of the word. Thanks...

Face Code
  • 203
  • 3
  • 12
  • 1
    I suppose you could parse the document's text on the page load, look for your keyword, wrap a span with an ID around it, then set the scroll top equal to the offset top of the newly created span – mhodges Aug 16 '16 at 21:47
  • 1
    @Adjit Maybe I wasn't clear enough. I don't want to highlight the word, I want to scroll the page to the first instance of the word. – Face Code Aug 16 '16 at 21:52
  • Ahh ok, I see. Well there are a few different things that you need to figure out then - [How to scroll to a specific element on a page](http://stackoverflow.com/questions/2905867/how-to-scroll-to-specific-item-using-jquery); So, first I would say [find the text of a string](http://stackoverflow.com/questions/926580/find-text-string-using-jquery), add a span element with that word, and then use the scroll to scroll to that element. – Adjit Aug 16 '16 at 22:03

2 Answers2

0

I had some fun with it. I added some comments inline. If anything isn't clear, feel free to ask.

var found = false;

function goToWord(word, context) {
  // Search all wrapper candidates
  $(context).each(function(i, el) {
    if (found) return;
    var $el = $(el);
    text = $el.text();
    // Substring matching
    if (~text.indexOf(word)) {
      found = true;
      $el.html(text.replace(word, "<span id='go-to-target'>" + word + "</span>"));
    }
  });

  // Only continue if we found something
  if (found) {
    animateTop(text);
  }
}

function animateTop(text) {
  var target = $("#go-to-target"),
    offTop = target.offset().top;

  // Animate to item
  $("html, body").animate({
    "scrollTop": offTop
  }, 300, function() {
    // Remove span
    target.replaceWith(text);
  });
}


goToWord("sodales", "p");
p {
  width: 360px;
  margin: 1.67em auto;
  font-size: 16px;
  line-height: 1.625;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta.
  Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </p>

<p>Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis. Sed convallis tristique sem. Proin ut ligula vel nunc egestas porttitor. Morbi lectus risus,
  iaculis vel, suscipit quis, luctus non, massa. Fusce ac turpis quis ligula lacinia aliquet. Mauris ipsum. Nulla metus metus, ullamcorper vel, tincidunt sed, euismod in, nibh. Quisque volutpat condimentum velit. </p>

<p>Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam nec ante. Sed lacinia, urna non tincidunt mattis, tortor neque adipiscing diam, a cursus ipsum ante quis turpis. Nulla facilisi. Ut fringilla. Suspendisse
  potenti. Nunc feugiat mi a tellus consequat imperdiet. Vestibulum sapien. Proin quam. Etiam ultrices. Suspendisse in justo eu magna luctus suscipit. Sed lectus. </p>

<p>Integer euismod lacus luctus magna. Quisque cursus, metus vitae pharetra auctor, sem massa mattis sem, at interdum magna augue eget diam. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Morbi lacinia molestie dui.
  Praesent blandit dolor. Sed non quam. In vel mi sit amet augue congue elementum. Morbi in ipsum sit amet pede facilisis laoreet. Donec lacus nunc, viverra nec, blandit vel, egestas et, augue. Vestibulum tincidunt malesuada tellus. Ut ultrices ultrices
  enim. Curabitur sit amet mauris. Morbi in dui quis est pulvinar ullamcorper. Nulla facilisi. Integer lacinia sollicitudin massa. </p>

<p>Cras metus. Sed aliquet risus a tortor. Integer id quam. Morbi mi. Quisque nisl felis, venenatis tristique, dignissim in, ultrices sit amet, augue. Proin sodales libero eget ante. Nulla quam. Aenean laoreet. Vestibulum nisi lectus, commodo ac, facilisis
  ac, ultricies eu, pede. Ut orci risus, accumsan porttitor, cursus quis, aliquet eget, justo. Sed pretium blandit orci. Ut eu diam at pede suscipit sodales. Aenean lectus elit, fermentum non, convallis id, sagittis at, neque. </p>

<p>Nullam mauris orci, aliquet et, iaculis et, viverra vitae, ligula. Nulla ut felis in purus aliquam imperdiet. Maecenas aliquet mollis lectus. Vivamus consectetuer risus et tortor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio.
  Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. </p>
Bram Vanroy
  • 27,032
  • 24
  • 137
  • 239
-1

You should start off by giving us some code you've tried before. If you don't know where to start break your issue down into simple parts: 'How to jump to a word jquery' etc.

Working Example

This isn't a perfect example and could be done better.

function goToWord(term) {
  $('body').html($('body').html().replace(term, '<span class="found">' + term + '</span>'));
  $('div').scrollTop($('.found').offset().top - 25);
}

goToWord('pear');

goToWord(term) - get term from the URL anyway you want and pass it to the function.

I've updated the snippet to search for the term in the the body's html rather than in all p tags

You'll need to replace $('div') with whatever the parent is in your document. Or you could replace it with $('body').

Wild Beard
  • 2,919
  • 1
  • 12
  • 24
  • Yes, this is basically what my comment was describing. My only beef with this is that realistically, every word in the page will not be wrapped in a tag (for obvious performance implications). You really should parse the HTML and wrap the word in a new tag, scroll to that tag, and then remove the tag – mhodges Aug 16 '16 at 22:03
  • @mhodges yeah I meant to add a snippet about this not being the best solution. – Wild Beard Aug 16 '16 at 22:04
  • Yeah, just simply mention it. It certainly makes the solution much more robust and adds to the complexity, which should be an exercise that is left to the OP. – mhodges Aug 16 '16 at 22:06