I use the jQuery dialog with position: fixed
on my website. On PC this dialog has the center position by default.
On mobile device, it sets the position to the top left. I tried different methods but it failed to position this dialog center on mobile.
Code:
CSS:
.ui-dialog {
position: fixed;
top: 0;
left: 0;
padding: .2em;
outline: 0;
}
JS:
function isMobileDevice() {
var mobileRegEx = new RegExp("Android|webOS|iPhone|iPad|iPod|BlackBerry", "i");
return mobileRegEx.test(navigator.userAgent);
}
$("#myDialog").dialog({
title: "Info",
closeText: "Close",
width: 440,
minWidth: 440,
height: 250,
minHeight: 250,
modal: true,
resizable: false,
open: function() {
if (isMobileDevice()) {
$(this).dialog("option", "position", { my: "center", at: "center", of: window });
}
}
});
Any ideas how to set it to the center on mobile device? Thank you for your help.
So, I have fixed it by myself. My solution is suitable for the 2 screen orientations: portrait and landscape.
document
instead of a window
: $(this).dialog("option", "position", { my: "center", at: "center", of: document, within: document });
This sets the dialog to the center of document in portrait mode and also sets the starting point for the landscape mode.mobileDlgPosition()
function, which checks for landscape mode. And if the device is in landscape mode, then it calculates and set the dialog top
position by using this method: (window.outerWidth - $(".ui-dialog").width()) / 2;
$(window).on("orientationchange")
function which checks for the dialog instance and if the dialog instance is available it runs mobileDlgPosition()
function.My code:
function isMobileDevice() {
var mobileRegEx = new RegExp("Android|webOS|iPhone|iPad|iPod|BlackBerry", "i");
return mobileRegEx.test(navigator.userAgent);
}
$(window).on("orientationchange", function() {
var dlgInstance = $("#" + $(".ui-dialog").attr("aria-describedby")).dialog("instance");
if (dlgInstance) {
mobileDlgPosition();
}
});
function mobileDlgPosition() {
if (window.screen.orientation.type != "portrait-primary") {
var landscapeTopPos = (window.outerWidth - $(".ui-dialog").width()) / 2;
$(".ui-dialog").css("top", landscapeTopPos + "px");
}
}
$("#myDialog").dialog({
title: "Info",
closeText: "Close",
width: 440,
minWidth: 440,
height: 250,
minHeight: 250,
modal: true,
resizable: false,
open: function() {
if (isMobileDevice()) {
$(this).dialog("option", "position", { my: "center", at: "center", of: document, within: document });
mobileDlgPosition();
}
}
});
I tested it on my phone - Xiaomi Mi 9. Everything works well.
Result: