My current code is
Test
When the window size is smaller than 640px, how can I change it a
Changing attributes won't convert a div into a panel, you need to initialize it manually. In jQuery Mobile 1.3, you should use .trigger("pagecreate")
when appending a panel dynamically in order to initialize it.
The below solution creates a panel and moves content div's elements when page's width is small; and it removes panel and returns content div's element to their original position. Also, it creates a button inside header to open the panel. It can be used in any page events as well as on window's throttledresize
and orientationchange
.
$(window).on("throttledresize", function () {
var activePage = $.mobile.activePage;
if ($(window).width() < 500 && activePage.find("[data-role=panel]").length === 0) {
/* create button */
var button = $("<a/>", {
"data-role": "button",
"data-icon": "bars",
"id": "panelBtn",
"data-theme": "e",
class: "ui-btn-left"
}).text("Panel");
/* add click listener to open panel
and append it to header */
activePage.find(".ui-header").append($(button).on("click", function () {
$("#left-panel").panel("open");
}));
/* save menu */
var menu = $("#menu");
/* create a panel
append menu
create page */
activePage.prepend($("<div/>", {
id: "left-panel",
"data-role": "panel",
"data-position": "left",
"data-display": "push"
}).append($("<div/>", {
class: "ui-panel-inner"
}).append(menu))).trigger("pagecreate");
}
if ($(window).width() > 500 && activePage.find("[data-role=panel]").length === 1) {
/* remove panel and button
return menu to content div */
if (activePage.hasClass("ui-page-panel-open")) {
activePage.find("[data-role=panel]").panel("close").on("panelclose", function () {
var menu1 = activePage.find("[data-role=panel] #menu");
activePage.find("[data-role=content]").append(menu1);
activePage.find("[data-role=panel]").remove();
activePage.find("#panelBtn").remove();
activePage.trigger("pagecreate");
});
} else {
var menu1 = activePage.find("[data-role=panel] #menu");
activePage.find("[data-role=content]").append(menu1);
activePage.find("[data-role=panel]").remove();
activePage.find("#panelBtn").remove();
activePage.trigger("pagecreate");
}
}
});
Demo
$(window).resize(function(){
if ($(this).width() < 640) {
var myDiv = $('#column-left');
if (myDiv.length > 0) {
myDiv.attr('id', 'left-panel').data('role', 'panel').data('position', 'left');
}
} else {
var myDiv = $('#left-panel');
if (myDiv.length > 0) {
myDiv.attr('id', 'column-left').data('role', '').data('position', '');
}
}
});