I’m teaching myself JQuery and as practice I’m creating a page in which the user enters text in an input field and all instances of that string is found in the body of the page and highlighted. I have been able achieve this functionality when the user clicks a button, but what I’d like to get it to do is continuously poll the input field and highlight the string.
Doing a continuous poll seems to crash the page.
$(document).ready(function(){
while(1==1){
var str = document.input.str.value;
$(function(){
$('p:contains('+str+')').each(function(){
var regex = new RegExp(str, "g");
$(this).html( $(this).html().replace( regex ,"<span class='hlt'>"+str+"</span>"));
});
});
}
});
Websites seem to have this kind of functionality all the time so I’m sure its doable, I just can’t seem to find any info on it.
Thanks a lot!
The reason this makes your page unresponsive is that JavaScript is generally run on the same thread as the UI. That is to say, if your JavaScript is running, the rest of the page will be unresponsive. What you really want to do is one of the following:
blurevent (which is fired when the input box loses focus)changeeventIf you want to observe every single change that may happen in the input box, I would recommend observing the keyboard events.
If you wanted the polling approach: