1

I have Side Navigation action in jQuery:

$(function openSidebar()) {
   document.getElementById("sidebar").style.width = "250px";
   document.getElementById("wrapper").style.marginLeft = "250px";
}

function closeSidebar() {
   document.getElementById("sidebar").style.width = "0";
   document.getElementById("wrapper").style.marginLeft= "0";
}

I need to change width from 250px to 100% on mobile devices. How can I get it on jQuery?

4
  • 2
    Why do you use document.getElementById with jQuery? Commented May 26, 2017 at 16:55
  • stackoverflow.com/questions/16050926/… Commented May 26, 2017 at 16:59
  • @PeterMader I just used the solution from w3schools.com/howto/howto_js_sidenav.asp You may have another suggestion in return? Commented May 26, 2017 at 20:53
  • @FilipKolendo, with jQuery, you normally use $(...) and selectors to find elements in the DOM. In your case, it would be $('#sidebar').css('width', '250px'). Check out the jQuery API documentation. Commented May 27, 2017 at 16:54

1 Answer 1

0
   if ($(window).width() < 768) {
       $(function openSidebar()) {
           document.getElementById("sidebar").style.width = "100%";
           document.getElementById("wrapper").style.marginLeft = "100%";
       }

       function closeSidebar() {
           document.getElementById("sidebar").style.width = "0";
           document.getElementById("wrapper").style.marginLeft = "0";
       }
   } else {
       $(function openSidebar()) {
           document.getElementById("sidebar").style.width = "250px";
           document.getElementById("wrapper").style.marginLeft = "250px";
       }

       function closeSidebar() {
           document.getElementById("sidebar").style.width = "0";
           document.getElementById("wrapper").style.marginLeft = "0";
       }
   }

Update:

       if ($(window).width() < 768) {
           var width = "100%";
           var marginLeft = "100%";
       } else {
           var width = "250px";
           var marginLeft = "250px";
       }

        function openSidebar() {
           $("#sidebar").width(width);
           $("#wrapper").css('margin-left', marginLeft );
       };
Sign up to request clarification or add additional context in comments.

16 Comments

Unfortunately, it does not work and highlights getElementById in two places
@FilipKolendo I added your function name.
It bugs me to no end when websites decide to arbitrarily assume some random width means you're on a mobile device.
Now it works with only 250px and marginLeft on #wrapper is 0px all the time :/
On mobile device it woks with 100% but on regular laptop margin left is still 0px
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.