1

If you visit Google.com and type in a letter in the search bar, it seemingly transports you to another page instantly. You can type as fast as possible during this time and Google doesn't lose a single character.

I've tried emulating this with keyup() events and setinterval() but I still end up losing a character or two by the time it loads the page.

$(document).ready(function(){
var timer;$("input#q").keyup(
  function(e){
  var str = $("input#q").val();
  if(str.length > 1){
    clearInterval(timer);timer = setTimeout(
      function(){var url = "/search/?q="+encodeURI($("input#q").val());
      location.href = url;}, 210);
   }
});

This is the code I'm currently using, it works but can lose a keypress/keyup when it transfers you to the next page.

Does anyone know how Google does it or have any suggestions?

Thanks

andyb
  • 42,062
  • 11
  • 113
  • 146
noko
  • 1,069
  • 2
  • 12
  • 25

3 Answers3

7

You think you are transported to another page, but in fact not. It uses pop/push in the history stack, using a new (cool!) HTML5 feature.

The page is never reloaded, so you do not loose any characters.

Github also uses it when you browse a repository.

Guillaume Poussel
  • 8,864
  • 1
  • 30
  • 39
  • Thanks for such a quick answer! Do you think you can rustle up some example code for this? – noko Sep 17 '12 at 12:00
  • I don't think I can use this feature with JSFiddle. Your best bet is to find a link in [this question](http://stackoverflow.com/q/4015613/263057). I found [this example](http://html5demos.com/history) particularly useful. Code is simple and should suit your needs. – Guillaume Poussel Sep 17 '12 at 12:03
  • @GuillaumePoussel I agree that when the _Enter_ key is pressed the history is pushed but I don't think the `keyUp()` events are pushing history. – andyb Sep 17 '12 at 13:45
1

The capturing of the input is actually done in the same <input> control, which is just moved by changing the CSS positioning. There is no page transition, only JavaScript to react to the key press and then manipulate the style accordingly.

There are AJAX events being fired in the background to perform the incremental search (if you have that option turned on for Google) which you can see if you use a browser that can show Network traffic, like Chrome for example.

andyb
  • 42,062
  • 11
  • 113
  • 146
  • I managed to emulate Google's behaviour by rearranging DOM on the fly. I generated new DIVs and remove()'d old ones before moving the input box around on the page. I think I can probably do something like this with the pop/push features. Still not 100% sure how to use it yet though. – noko Sep 18 '12 at 10:20
0

From what I can see when using google.com, they don't actually alter the location in the bar until you leave the search box. At this point it does a quick alteration of the in-page anchor (After the #), which won't trigger a full reload of the page.

Joakim Johansson
  • 2,922
  • 1
  • 24
  • 42