0

I have this code:

<script type='text/javascript' src='//code.jquery.com/jquery-1.9.1.js'></script>
<script type='text/javascript'>
//<![CDATA[ 
$(window).load(function(){
$('#content-left').css('width', '100%').css('width', '-=320px');
$(window).on('resize', function(){
$('#content-left').css('width', '100%').css('width', '-=320px');
});
});
//]]>  
</script>

The above code works great but what I need is for this code to stop working or switch back to just 100% width (without subtracting the 320px) when the screen size is 768px or less.

I did some google searches and found this:

if ($(window).width() <= 768){  
        // do something here
    }

But I'm not sure how to add this to my existing code.


Background:

My sidebar is a fixed sidebar on the right side of the page at 300px. And I have a padding of 20px between the sidebar (#content-right) and the main section (#content-left). My main section (#content-left) is using the above script of 100% - 320px.

I am using two CSS. One is a regular CSS. The other uses:

@media all and (max-width: 768px) {}

Thank you. :)

SomeDude
  • 27
  • 6
  • Are you limited to just using JavaScript or would you be willing to entertain a CSS solution? – Patrick Dec 11 '14 at 19:54
  • I tried using width: calc (100% - 320px) in CSS. But I noticed issues with browser compatibility. So I found the JavaScript mentioned in the question. But I am open to any solution. – SomeDude Dec 11 '14 at 19:58
  • Beware: http://stackoverflow.com/questions/11309859/css-media-queries-and-javascript-window-width-do-not-match In fact you should use `window.matchMedia` See this answer too: http://stackoverflow.com/a/23243951/1414562 – A. Wolff Dec 11 '14 at 20:20

2 Answers2

0

You can combine them like this. This only runs your code when the window is NOT less than 769 pixels. That's what the "!" symbol does, converts it to NOT.

$(window).load(function() {
  if (!$(window).width() <= 768) {
    $('#content-left').css('width', '100%').css('width', '-=320px');
    $(window).on('resize', function() {
      $('#content-left').css('width', '100%').css('width', '-=320px');
    });
  }
});
Ian Hazzard
  • 7,661
  • 7
  • 34
  • 60
0

Use a simple if/else statement, put your resize code in a function and call that function when the page loads and when the window is resized.

function resize() {
  if ($(window).width() <= 768) {
    $('#content-left').css('width', '100%');
  } else {
    $('#content-left').css('width', '100%').css('width', '-=320px');

  }
}

$(window).load(function() {
  resize();
});
$(window).on('resize', function() {
  resize();
});
Weafs.py
  • 22,731
  • 9
  • 56
  • 78