SeeleyBoothe
SeeleyBoothe

Reputation: 261

Jquery Mobile inserting buttons trhough javascript loses Styles

So I am dynamically creating a list of button and then inserting them into a div in jquery mobile page. Problem is when they are inserted they are no longer styled with as they would be if I just manually entered them in the html. Here is the code for what I am doing:

function iabGetURLs(){
var allURLs = window.localStorage.getItem("iabURLs");
html = "";
tmpURLs = allURLs.split(",");
for(var z=0;z<tmpURLs.length;z++){
    var urlParts = tmpURLs[z].split("|");
    html += '<input type="button" rel="' + urlParts[0] + '" class="iabListButton_' + z + '" value="' + urlParts[1] + '" />';    
}
$(".iabList").html(html); //puts it in the div

Click function:

$("[class^=iabListButton_]").click(function(){
    $this = $(this);
    $goURL = $this.attr('rel');
    startBrowser($goURL); 
 });

Upvotes: 0

Views: 50

Answers (1)

peterm
peterm

Reputation: 92785

After you dynamically add content you need to either call a .button() method on every button individually or call trigger('create') on a parent to enhance all newly added elements.

Try change

$(".iabList").html(html);

to

$(".iabList").html(html).trigger("create");

UPDATE: Since you inject button's markup for them in order to work you need to use event delegation to attach an event handler to the nearest static (not changing) parent element. In your case it seems to be $(".iabList"). That being said change

$("[class^=iabListButton_]").click(function(){
...
});

to

$(".iabList").on("click", "[class^=iabListButton_]", function(){
...
});

Read more .on()

You might need to detach a handler with .off() first

$(".iabList").off("click", "[class^=iabListButton_]").on("click", "[class^=iabListButton_]", function(){
...
});

Upvotes: 1

Related Questions