Home > front end >  Get one jQuery media query to fire
Get one jQuery media query to fire

Time:01-27

I have three CSS @media queries and I need to run some JavaScript to measure the height of a div and move a second div on some screen sizes. The issue is that all of my queries are applying, obviously because they all return true. How can I adjust this so that only one of the conditionals fire in jQuery, similarly to CSS?

//Responsive Adjustments
jQuery(document).ready(function($) {
  $(window).resize(function () {
    console.log($(window).width());
    
    if ($(window).width() <= 1024) {
      console.log ('tab land');
    }

    if ($(window).width() <= 980) {
      console.log ('tab port');
    }

    if ($(window).width() <= 479) {
      console.log ('phone port');
    }
  });
});

CodePudding user response:

Use else if and check from mobile upwards:

//Responsive Adjustments
jQuery(document).ready(function($) {
  $(window).resize(function() {
    console.log($(window).width());

    if ($(window).width() <= 479) {
      console.log('phone port');
    } else if ($(window).width() <= 980) {
      console.log('tab port');
    } else if ($(window).width() <= 1024) {
      console.log('tab land');
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

CodePudding user response:

You could adjust your conditions:

//Responsive Adjustments
jQuery(document).ready(function($) {
  $(window).resize(function() {
    console.log($(window).width());

    if ($(window).width() <= 1024 && $(window).width() > 980) {
      console.log('tab land');
    }

    if ($(window).width() <= 980 && $(window).width() > 479) {
      console.log('tab port');
    }

    if ($(window).width() <= 479) {
      console.log('phone port');
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  •  Tags:  
  • Related