Busca específica em texto usando jQuery
Nem todo usuário conhece o atalho ctrl+F (buscar) que está presente em quase todos os apps de hoje em dia.
Por esse motivo, é sempre válido criar uma caixinha de busca em páginas que contém muito texto. Busca específica em texto usando jQuery mostra como alcançar essa funcionalidade.
Para este demo foi usado o jQuery highlight Plugin do Johann Burkard.
HTML
<html> <head> <meta name="robots" content="noindex, nofollow"/> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script type="text/javascript" src="scripts/page.js"></script> <link href='css/style.css' rel="stylesheet" type="text/css"/> <title>Busca com JQuery</title> </head> <body> <div id="keys"> <div id="searchBox"> <input type="text" id="txtsearch" placeholder="search" name="search"/> <div id="btnsearch" title="Buscar no texto"></div> <div class="break"></div> <div class='back-top'>inicio ↑</div> </div> <h1>Texto a ser pesquisado</h1> <section> TEXTO AQUI </section> <script src="scripts/jquery.highlight-4.closure.js" type="text/javascript"></script> </body> </html>
CSS
#searchBox{ position: fixed; top: 0; right: 0; width: 190px; background-color: #000; box-shadow: 0 0 8px #ccc; padding: 0 5px 10px 0; margin: -4px 0 0 0; border-radius: 4px; color: #fff; text-align: right; } #searchBox a{ color:#fff !important; } #txtsearch { border: 4px solid #000; line-height: 35px; font-size: 14px; padding-left: 10px; font-family: 'Segoe UI'; border-bottom-right-radius: 8px; border-bottom-left-radius: 8px; float:left; margin-left:5px; } #txtsearch:focus{ outline:none; } #btnsearch{ background:url('../images/search.png') no-repeat center; background-size: 24px; width: 24px; height: 24px; float:left; cursor: pointer; z-index: 999999; margin: 10px 0 0 -40px; } .highlight { background-color: #F6E8B9; font-weight: bold; } .back-top{ color:#fff; font-weight: bold; padding-left:15%; cursor: pointer; transition:letter-spacing 0.3s ease; } .back-top:hover{ letter-spacing:3px; } #txtsearch { border: 1px solid #000; line-height: 18px; font-size: 16px; padding-left: 10px; font-family: 'Segoe UI'; border-bottom-right-radius: 8px; border-bottom-left-radius: 8px; float:left; } #btnsearch{ background:url('../images/search.png') no-repeat center; background-size: 16px; width: 16px; height: 16px; float:left; cursor: pointer; z-index: 999999; margin: 7px 0 0 -25px; }
jQuery
var counter = 0; $(function(){ $('.back-top').click(function(){ $('html, body').animate({ scrollTop: 0 }, 300); }); $("#btnsearch").click(function(e){ $("body").removeHighlight(); $("body").highlight($("#txtsearch").val()); var curr = $('.highlight')[counter]; var top = $(curr).offset().top-180; $('html, body').animate({ scrollTop: top }, 300); counter++; if(counter>=$('.highlight').length)counter=0; }); $("#txtsearch").click(function(){ $(this).select().focus(); }); $("#txtsearch").keypress(function(e){ if(e.which===13) { $("#btnsearch").click(); }; }); })
Veja o Demo