Answer the question
In order to leave comments, you need to log in
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 );
}
});
});
Answer the question
In order to leave comments, you need to log in
$(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 questionAsk a Question
731 491 924 answers to any question