Search code examples
javascriptcssasp.nettoggleclassasp.net-controls

How can I toggle a css class automatically on mobile view?


I would like to automatically toggle an asp.net control (Textbox) class when a user opens the website on mobile.

I tried the following code it works to get the screen size automatically. but now I want to change or add a new class to the textbox which sets the Textbox width to 100%.

Javascript code

<script type="text/javascript">
window.onload = function () { responsiveFn(); }
function responsiveFn() {
width = $(window).width();
height = $(window).height();

if (width <= 470)
{
var cntltxtInput = document.getElementById(<%=TextBox1.ClientID %>);
cntltxtInput.setAttribute("class", "mobMini");
document.getElementById('widthID').innerHTML += "This is an Iphone S";
}
}
</script>

Asp.net C#

<asp:TextBox ID="TextBox1" runat="server"  ></asp:Textbox>

Css Class

<style type="text/css">
.mobMini {
width:100%;
}
</style>

Any ideas?


Solution

  • Detecting mobile is awful - and I'd avoid it if you can. However, if you'd like to detect a screen size you should use CSS Media Queries.

    Add a class to your HTML (ASP):

    <asp:TextBox ID="TextBox1" runat="server" class="altMobile" ></asp:Textbox>
    

    Then use CSS on that class

    @media screen and (max-width:470px) {
        .altMobile {
            width: 100%
        }
    }
    

    PS: It's also important to note that many mobile browsers will try to pretend to be higher resolution than they are. To tell browsers not to, you must add meta viewport:

    <meta name="viewport" content="width=device-width, initial-scale=1" />