Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polling input field in Javascript

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!

like image 545
danem Avatar asked May 30 '26 00:05

danem


1 Answers

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:

  • Using the blur event (which is fired when the input box loses focus)
  • Using the change event
  • Using keyup/keydown events
  • Polling the input box in a non-blocking fashion using setTimeout or setInterval

If you want to observe every single change that may happen in the input box, I would recommend observing the keyboard events.

$(document).ready(function(){
    $('#inputID').keyup(function(){
        $('p:contains('+str+')').each(function(){
                 var regex = new RegExp(str, "g");
                 $(this).html( $(this).html().replace( regex ,"<span class='hlt'>"+str+"</span>")); 
        });
    });
});

If you wanted the polling approach:

$(document).ready(function(){
    var intervalID = setInterval(function(){
        //execute logic here
    }, 100); // 100 ms check
});
like image 126
Matt Avatar answered May 31 '26 12:05

Matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!