views:

50

answers:

3

I have a search box on a page that's hooked up to an AJAX script that returns HTML based on the contents of the search box, via GET.

In order to display the results directly below the search box, I need to create a div in a position relative to that box (the box's position is variable depending on screen resolutions). How can I use jQuery to achieve this?

Alternatively, can jQuery UI Autocomplete be used instead and if so, how? I did have a bash with it but had trouble getting it to display the HTML at all.

Edit: Here is a jsfiddle link: http://jsfiddle.net/UxPb8/

You can be forgiven for thinking it works but as soon as there's more stuff on the page to the left of the search box, the positioning is thrown off, hence this question.

+2  A: 

Say your search box is in a div called 'search'.

Then you can use the jQuery after function to append your html:

$('#search').after(html);

If the 'div' you want to create isn't part of the returned HTML, it's pretty easy to insert it:

$('#search').after("<div>" + html + "</div>");
sje397
A: 

Like this..(after returned html)

$('.classNameORID').append("<div style='position:relative;'>"+ data +"</div>");
Oyeme
Append will insert the div and its contents to the end of the CONTENTS of the search box, not after it. That is why @sje397 has the correct answer. Also, .classNameORID is not a good example, because the dot would only work for a class name. Other than that, pretty good.
Daniel Dyson
Yes,I mean .classNameORID it's for class only and # for ID.
Oyeme
A: 

I ended up doing this:

//calculate the position
var parentDiv = $(this).parents(selector);
var top = parentDiv.position().top + parentDiv.height();
var left = $("#wrapper").width()-427; //427 is a fixed offset - it's still in the right place for any screen res

//run the search
$.ajax({
    url: 'ajax/find.php',
    data: { search: $(this).val() },
    success: function(data) {
        $("#globalFindResults")
            .css({
                'position': 'absolute',
                'top': top,
                'left': left
                })
            .html(data)
            .slideDown('fast');
    }
});
bcmcfc