Link to home
Start Free TrialLog in
Avatar of colonelblue
colonelblue

asked on

How to get autofocus in the search field using Google's Search Engine on a site.

Hello Experts,

I'm using Google's Search Engine on a site I'm working on.
I have placed it in a div.
However there is no autofocus and the client has to click in the search box.
How do I make it so that the cursor is automatically in the search box.

I've tried appending ".autofocus()" but perhaps I'm not adding it to the correct part of the code.


Thanks again Experts. You guys really rock.


Here is the code.

The placeholder for the searchbox
<gcse:searchbox-only></gcse:searchbox-only> 

Open in new window




Their script
 <script>
  (function() {
    var cx = 'xxxxyyzz';
    var gcse = document.createElement('script'); gcse.type = 'text/javascript'; gcse.async = true;
    gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
        '//www.google.com/cse/cse.js?cx=' + cx;
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gcse, s);
  })();
</script>

Open in new window

Avatar of Robert Schutt
Robert Schutt
Flag of Netherlands image

I tried it out and added this code below line 7 in the script block:
setTimeout("document.getElementById('gsc-i-id1').focus();", 1000);

Open in new window

Note that this is not the cleanest solution.
Avatar of colonelblue
colonelblue

ASKER

Hello Robert and thank you.
I added it under line 7 but I don't see a chane.
Perhaps I am doing something wrong?
Well, like I said it's not a clean solution, maybe you need to wait longer (try 2000 instead of 1000).

Also, please check the generated code on your site, for example with F12 tools in IE or Firebug in Firefox, shouldn't be different for you or me unless the settings have something to do with it, I found the id of the textbox from the html that is generated:User generated image
I will check as soon as I get back to the office. Curious dies it make a difference that the search box is initially loaded as a hidden div and then shown as soon as the search text link is clicked via an onclick function?
ASKER CERTIFIED SOLUTION
Avatar of Robert Schutt
Robert Schutt
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Robert you are the man!! :)
Happy Dance here.

That worked like a charm!
Thank you so much!!!
Woo-hoo! :)
Haha, fantastic again to see your enthusiasm! Makes me glad to be able to help as well :-B