Rik
Rik

Reputation: 223

Binding jQuery slider after DOM manipulation

I'm using some sliders from jQuery UI. They work fine when I bind them on "static" HTML divs, however, I want to bind them on a few dynamically loaded divs. Let me explain this in some example code:

<script type="text/javascript"> 
function addThing(id)
{
    // retrieve some data from a json source
    $.getJSON('/get/thing/' + id + '/', function(jsondata) 
    {
        var newtd = '<td><div class="slider" id="sl'+id+'"></div></td>';
        $("#tbody_tr").append($(newtd));
    }

    // method 1    
    $( "#sl"+id ).slider();
    // method 2    
    $( ".slider" ).slider();
}

addThing(1);
</script>

So this works, except for the sliders. I can't seem to figure this out. Please give me some pointers!

Upvotes: 1

Views: 675

Answers (1)

epascarello
epascarello

Reputation: 207501

You need to do it in the callback and not in the function. The $( "#sl"+id ).slider(); is happening before the elements are added to the page. It is asynchronous, not synchronous.

function addThing(id)
{
    // retrieve some data from a json source
    $.getJSON('/get/thing/' + id + '/', function(jsondata) 
    {
        var newtd = '<td><div class="slider" id="sl'+id+'"></div></td>';
        $("#tbody_tr").append($(newtd));
        $( "#sl"+id ).slider();
    }
}

addThing(1);

Upvotes: 1

Related Questions