Reputation: 45
I have an html page where there are many jquery mobile panels. Now i need to create new panel from javascript dynamically. All of panels are in a div with a specific id. I use getElementById, than innerHtml to append the new div at runtime.
The problem is that the jquery div should't appear until i click the link that opens it. But when i inner the jquery div from javacript it is showed as a normal div. It seems that the jquery mobile scripts doesn't recognized the new divs that i add at runtime. can anyone helps me?
Thanks very much.
Here a simple example of the problem:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<div id="panels">
<div data-role="panel" id="myPanel">
<h2>Panel Header</h2>
<p>You can close the panel by clicking outside the panel, pressing the Esc key or by swiping.</p>
</div>
</div>
<a href="#myPanel" class="ui-btn ui-btn-inline ui-corner-all ui-shadow">Open Panel</a>
<a href="#myPanel2" class="ui-btn ui-btn-inline ui-corner-all ui-shadow">Open Panel2</a>
</body>
<script type="text/javascript">
//now when an event is verified i inner the new jquery mobile panel
e.addEventListener("click", function(){
document.getElementById("panels").innerHTML+=' <div data-role="panel" id="myPanel2">
<h2>Panel Header</h2>
<p>Text</p>
</div>';
}, false);
</script>
</html>
Upvotes: 2
Views: 2037
Reputation: 24738
After dynamically adding the panel, you need to tell jQuery Mobile to initialize it. One way is to call enhanceWithin() on the panels container:
$("#btnAdd").on("click", function () {
var panel = '<div data-role="panel" id="myPanel2"><h2>Panel Header</h2><p>Text</p></div>';
$("#panels").append(panel).enhanceWithin();
});
Another way is to call the panel() widget initializer directly on the newly added panel div;
$("#btnAdd").on("click", function () {
var panel = '<div data-role="panel" id="myPanel2"><h2>Panel Header</h2><p>Text</p></div>';
$("#panels").append(panel);
$("#myPanel2").panel();
});
Upvotes: 3