1

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?

rebo lavo
  • 179
  • 1
  • 2
  • 13
  • 1
    Rather than using JavaScript, why not use CSS media queries? – mason Apr 25 '15 at 23:08
  • Thanks, actually I've tried to use that, and even using bootstrap. but I'm stuck in one point . I also posted this question you may see where is my problem http://stackoverflow.com/questions/29868198/textbox-and-button-levels-in-mobile-view – rebo lavo Apr 25 '15 at 23:13
  • and I was told, that the java script could solve this. The code works for tablet and desktop. but It only has problem on Iphone. – rebo lavo Apr 25 '15 at 23:14
  • 1
    I don't see anyone there telling you JavaScript could solve this. Even if someone else told you, that doesn't make it a good idea. CSS is what's primarily used to style web pages. CSS Media Queries are the tool used to target CSS at specific device sizes. Look into that, and you'll likely find your answer. – mason Apr 25 '15 at 23:15
  • Thanks, it's been solved using Media Query with screen sizes. – rebo lavo Apr 25 '15 at 23:48
  • You should post your solution here, for others that may have your question. – mason Apr 25 '15 at 23:49

1 Answers1

2

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" />
rebo lavo
  • 179
  • 1
  • 2
  • 13
Cosine
  • 572
  • 4
  • 18