Search code examples
javascriptjqueryjquery-uitabsjquery-tabs

Append jQuery tabs inside a div that's created with javascript


I want to use jQuery tabs (http://jsfiddle.net/43FcS/2/) inside a div that's created with javascript.

Right now I'm creating a shop locator for a shop that I'm working at. I'm using the jQuery shop locator plugin, created by Bjorn (http://www.bjornblog.com/web/jquery-store-locator-plugin).

When the user clicks search the search results (4 closest shops to the entered address) will be listed. In each li I thought of creating a div with a class "shoptab". In each div I want to have the 2 tabs (address and opening hours) shown, as in the link above. My javascript creates the li with the following function:

$('<li />').html("<div class=\"shoptab\"><h2 class=\"loc-name\"> Shop " + storeName + "<\/h2> <ul><li><a href=\"#tabs-1\">Address<\/a><\/li> <li><a href=\"#tabs-2\">Opening hours<\/a><\/li><\/ul> <div id=\"tabs-1\"><p>" + storeAddress1 + "<\/p> <p>" + storeAddress2 + "<\/p> <p>" + storeCity + ", " + storeState + " " + storeZip + "<\/p> <p>" + storePhone + "<\/p> <\/div> <div id=\"tabs-2\"><p>" + storeHours1 + "<\/p> <p>" + storeHours2 + "<\/p> <p>" + storeHours3 + "<\/p> <\/div><\/div>")

I know I cannot use the ids tabs-1 and tabs-2 as they would be used several times, but for now I just wanted them to atleast show up and then afterwards adjust the code to give the div's ids 1,2,3,4 etc.

My function to the jQuery tabs is written at the bottom of the document together with my shoplocator function.

$(function() {
        $(".shoptab").tabs();
    });

The jQuery ui script doesn't apply the classes to the shoptab div and ul/li within and I can't figure out how to make it work.

I hope with this information you can help me out.


Solution

  • I think the problem is that $(".shoptab").tabs(); is called before there is required html present in the document.

    You should call $(".shoptab").tabs(); after you have inserted the HTML in the document i.e. after all of the

    $('<li />').html("<div class=\"shoptab\"><h2 class=\"loc-name\"> Shop " + storeName + "<\/h2> <ul><li><a href=\"#tabs-1\">Address<\/a><\/li> <li><a href=\"#tabs-2\">Opening hours<\/a><\/li><\/ul> <div id=\"tabs-1\"><p>" + storeAddress1 + "<\/p> <p>" + storeAddress2 + "<\/p> <p>" + storeCity + ", " + storeState + " " + storeZip + "<\/p> <p>" + storePhone + "<\/p> <\/div> <div id=\"tabs-2\"><p>" + storeHours1 + "<\/p> <p>" + storeHours2 + "<\/p> <p>" + storeHours3 + "<\/p> <\/div><\/div>") 
    

    has executed