YUI Library Home

YUI Library Examples: AutoComplete Control: Centering AutoComplete On a Page

AutoComplete Control: Centering AutoComplete On a Page

This example points to Yahoo! Search Web Services. To achieve the shrink-wrapped, centered search module, custom CSS rules have been applied, and the method doBeforeExpandContainer has been customized to position the container directly below the input field.

Sample Code

CSS:

1/* custom styles for centered example */ 
2body, h1 { margin:0;padding:0} /* needed for known issue with Dom.getXY() in safari for absolute elements in positioned containers */ 
3#ysearch { text-align:center} 
4#ysearchinput { position:static;width:20em} /* to center, set static and explicit width: */ 
5#ysearchcontainer { text-align:left;width:20em} /* to center, set left-align and explicit width: */ 
view plain | print | ?

Markup:

1<form action="http://search.yahoo.com/search"
2    <div id="ysearch"
3        <label>Yahoo! Search: </label> 
4        <input id="ysearchinput" type="text" name="p"
5        <input id="ysearchsubmit" type="submit" value="Submit Query"
6        <div id="ysearchcontainer"></div> 
7    </div> 
8</form> 
view plain | print | ?

JavaScript:

1YAHOO.example.Centered = function() { 
2    var myDataSource = new YAHOO.util.XHRDataSource("assets/php/ysearch_proxy.php?output=json&"); 
3    myDataSource.responseSchema = { 
4        resultsList: "ResultSet.Result"
5        fields: ["Title"
6    }; 
7 
8    // Instantiate AutoComplete 
9    var myAutoComp = new YAHOO.widget.AutoComplete("ysearchinput","ysearchcontainer", myDataSource); 
10    myAutoComp.queryMatchContains = true
11    myAutoComp.queryQuestionMark = false
12    myAutoComp.useShadow = true
13     
14    // Keeps container centered 
15    myAutoComp.doBeforeExpandContainer = function(oTextbox, oContainer, sQuery, aResults) { 
16        var pos = YAHOO.util.Dom.getXY(oTextbox); 
17        pos[1] += YAHOO.util.Dom.get(oTextbox).offsetHeight + 2; 
18        YAHOO.util.Dom.setXY(oContainer,pos); 
19        return true
20    }; 
21     
22    return { 
23        oDS: myDataSource, 
24        oAC: myAutoComp 
25    }; 
26}(); 
view plain | print | ?

Configuration for This Example

You can load the necessary JavaScript and CSS for this example from Yahoo's servers. Click here to load the YUI Dependency Configurator with all of this example's dependencies preconfigured.

Copyright © 2009 Yahoo! Inc. All rights reserved.

Privacy Policy - Terms of Service - Copyright Policy - Job Openings