Search code examples
javascripthtmlposition

Using positions with jquery for mobile browsers


I want to do something like fixed position, except for all mobile phones.

Like this:

Desktop:

#sidebar{
position:fixed;
width: 200px;
height: auto;
...

And mobile:

#sidebar{
position:absolute;
width: 200px;
height: auto;
...

So i'm wondering, if I use jquery or javascript, something like if mobile: use position absolute, if desktop: use position fixed, it might work.

But I'm not very good at programming javascript etc. I just know html and css. Could anyone help me with what codes I have to use?


Solution

  • You can use JavaScript/jQuery.

    This will check if the page is being viewed on a mobile browser and then apply the necessary changes.

    if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
      $("#sidebar").css("position", "absolute");
    }
    

    If you prefer a different method, you can check the height and width of the window:

    if(window.innerWidth <= 800 && window.innerHeight <= 600) {
      $("#sidebar").css("position", "absolute");
    }