The logic is as follows:
- create an element, for example,
span
, in which we will place the word for selection, and the corresponding styles; - on the text field, you must hang up the event handler pressing the keyboard. You are lucky and the choice of events you have is wide:
- keyboard
onkeyup
, onkeydown
and onkeypress
keyboard onkeypress
; - or even such events :
oninput
(this will work for any change in the text field), onchange
, onpaste
, etc. - in special cases they can be combined;
- in the handler, we check, for example, using a regular expression , whether the entered word is included in the analyzed text;
- if it is included, then we replace in the
innerHTML
text of the occurrence of words with the element created in paragraph 1, inside which we put the characters to be selected; - if not included, then remove all previous selections, if any. In the example, I simply replaced all the text with the original one.
The solution is suitable for small texts guaranteed. In the case when it is large, it will be necessary to carefully arrange the word replacement algorithm, but the code is valid. The regular expression, winking slyly with the i
key, ignores case.
var $input = $("#input"); var $text = $(".text"); // Сохраним изначальный текст var textOriginal = $text.text(); // Элемент, который задаст стили для выделения var $span = $('<span class="highlight">'); // Было ли уже выделение в тексте var hasChanges = false; $input.on('input', function(e) { var searchKey = $input.val(); // Можно обернуть в try{} catch, но так быстрее. Если в регулярке только один // один символ '\', то RegExp выбрасывает ошибку var regExp = new RegExp(searchKey == '\\' ? '' : searchKey, 'gi'); var textNew = textOriginal; // Если нет совпадений в тексте if (!regExp.test(textOriginal)) { if (hasChanges) { hasChanges = false; $text.text(textNew); } return true; } hasChanges = true; $text.html(textNew.replace(regExp, function(match) { $span.text(match); return $span[0].outerHTML; })); });
.highlight { background-color: yellow; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="input"> <br> <div class="text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat mollitia, nam voluptatibus maxime sed, illum veniam harum quos? Rerum consectetur quia quaerat quos id. Aliquam repudiandae ducimus asperiores iusto illum!</div>