I'm looking for some advice for the best way to do this.
Basically I have some javascript that detects if the user is on a mobile device, if they are a css file is loaded, a mobile class is added to the page's body, and a hidden field is given a value of mobile. Then I check the value of this hidden field so I can run methods specific to mobile devices.
Currently I have everything working as desired but I'm forced to do a javascript postback on the first page load so the the hidden field's value can be accessed from the code behind. I'm just wondering if there's a better way to do this?
Here's a bit of my code.
if ( navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i)) {
$("body").addClass("mobile");
$('head').append('<link rel="stylesheet" href="Styles/mobile.css" type="text/css" />');
$('head').append('<meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0;">');
if ($("#hfdevice").val() != "mobile")
{
$("#hfdevice").val("mobile");
__doPostBack('hfdevice','');
}
}
.
HiddenField hfdevice = (HiddenField)Master.FindControl("hfdevice");
if (hfdevice.Value == "mobile")
{
Do Stuff
}
If you don't want to use responsive design, you can detect user agent like they mentioned in comments. Code behind would be:
string theAgent = Request.UserAgent;
... run your check to see if mobile... change functionality, set cookie, etc.
You could also do this in the global.ascx and load a different MasterPage (a mobile master page) if you wanted.