Question

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.

Was it helpful?

Solution 3

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');
    }
});

OTHER TIPS

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>");

Like this..(after returned html)

$('.classNameORID').append("<div style='position:relative;'>"+ data +"</div>");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top