S
S
Smeecy Smeecy2018-01-30 13:42:48
css
Smeecy Smeecy, 2018-01-30 13:42:48

Scrolling to a word from a search?

The site has a search that highlights all the words that have been entered in the search box. This is implemented using the highlights.js library and the script:

$(function() {
    $('#text-search').bind('keyup change', function(ev) {
        // pull in the new value
        var searchTerm = $(this).val();
        // remove any old highlighted terms
        $('body').removeHighlight();
        // disable highlighting if empty
        if ( searchTerm ) {
            // highlight the new term
            $('body').highlight( searchTerm );
        }
    });
});

How to make the word not only highlighted, but after pressing the enter key, scrolling to this word occurs? Something like ctrl+F is obtained.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nick Sdk, 2018-01-30
@Wekeed

$(function() {
  $('#text-search').unbind().bind('keyup change', function(e){
    if (e.keyCode == 13){
      e.preventDefault();
      console.log($('span.highlight.viewed'));
      var highlights = $('span.highlight');
      if (highlights.length){
        var viewed = $('span.highlight.viewed');
        if (viewed.length >= highlights.length){
          viewed.removeClass('viewed');
          viewed = $('span.highlight.viewed');
        }
        if (viewed.length < highlights.length){
          var noViewed = highlights.parent().find('span.highlight:not([class*="viewed"])');
          var firstNoViewed = noViewed.first();
          var searchPosition = firstNoViewed.offset();
          var searchPositionTop = searchPosition.top;
          var windowHeight = window.innerHeight;
          var windowHeightHalf = windowHeight / 2;
          var scrollPosition = (searchPositionTop > windowHeightHalf) ? (searchPositionTop - windowHeightHalf) : 0;
          window.scrollTo(0, scrollPosition);
          firstNoViewed.addClass('viewed');
        }
      }
    } else {
      var searchTerm = $(this).val();
      $('body').removeHighlight();
      if (searchTerm){
        $('body').highlight(searchTerm);
      }
    }
  });
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question