Skip to content

Instantly share code, notes, and snippets.

@nmeylan
Last active August 29, 2015 14:05
Show Gist options
  • Save nmeylan/32ce6555790dd052b91d to your computer and use it in GitHub Desktop.
Save nmeylan/32ce6555790dd052b91d to your computer and use it in GitHub Desktop.
A mac osx like highlight search. Override ctrl + f browser behaviour.
function highlight_search() {
var search_box = $('#highlight_search');
var input = search_box.find('input');
search_box.keydown(function (e) {
highlight_result(e, input)
});
$('html').keydown(function (e) {
var ctrl = e.ctrlKey, cmd = e.metaKey, f3_key = 114, f_key = 70;
if (e.keyCode === f3_key || ((ctrl || cmd) && e.keyCode === f_key)) {
e.preventDefault();
if (search_box.is(':visible')) {
close_highlight_search(search_box);
} else {
$('html').append('<div id="searchMask" style="position: fixed; top: 0px; left: 0px; width: 1905px; height: 100%; display: block; opacity: 0.3; z-index: 10; background-color: rgb(0, 0, 0);"></div>').keydown(function (e) {
if (e.keyCode === 27) close_highlight_search(search_box);
});
search_box.css('display', 'block').css('z-index', ' 9999');
input.focus();
}
}
});
}
function close_highlight_search(search_box) {
search_box.css('display', 'none');
$('#searchMask').remove();
}
function highlight_result(event, input) {
var c = '';
var typed_key = String.fromCharCode(event.which);
if (typed_key.match(/^[a-z0-9'^éàèüäö]+$/i)) {
c = typed_key;
}
var filter = input[0].value + c;
if (event.keyCode === 8) {
filter = filter.substring(0, filter.length - 1);
}
$('.highlight').removeClass('highlight');
if (filter.trim() !== '') {
var count = 0;
var matches = $('* :contains("' + filter + '"):visible').filter(function (index) {
return $(this).children().length < 1;
});
var matches_size = matches.length;
count += matches_size;
if (matches_size > 0 && matches_size < 50) {
matches.each(function (a) {
$(this).addClass('highlight');
});
}
matches = $('a:visible:contains("' + filter + '")');
matches_size = matches.length;
count += matches_size;
if (matches_size > 0 && matches_size < 50) {
matches.each(function (a) {
$(this).addClass('highlight');
});
}
}
}
<div id="highlight_search">
<input type="text" name="highlight_search">
</div>
#highlight_search{
top: 56px;
position: fixed;
right: 0px;
display: none;
}
.highlight{
position: relative !important;
z-index: 20;
text-shadow: 0 0 10px #fff, 0 0 20px #fff, 0 0 30px #fff, 0 0 40px #fff !important;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment