5

Is it possible to add media jquery's into your jquery code?

I need to reduce "slideWidth: 83," when my screen hits a size of 800px;

$(document).ready(function(){
  $('.slider4').bxSlider({
    slideWidth: 83,
    minSlides: 2,
    maxSlides: 9,
    moveSlides: 1,
    slideMargin: 15
  });
});

4 Answers 4

9

Media queries are supported in js via window.matchMedia

This allows you to create something like

var isPortrait = window.matchMedia("(orientation: portrait)");
if (isPortrait.matches){
    // Screen is portrait
}

or

var smallScreen = window.matchMedia("(max-width: 480px)");
if (smallScreen.matches){
    // Screen is less than 480px
}

Support is good within modern browsers and there is a polyfill available as well but it doesn't support resizing out of the box.

More info – https://developer.mozilla.org/en-US/docs/Web/API/Window.matchMedia

Sign up to request clarification or add additional context in comments.

Comments

6

No, but you can measure the current width of the window and configure your code based on that:

if ($(window).width()<768) {
   // do whatever
}

If you need it to be responsive, tie your code to the window.onresize event as well:

$(window).on('resize', function() {
    if ($(window).width()<768) {
        // do whatever
    }
});

Comments

1

You cant explicitly have media queries, but you can check the window width with this little code :

function viewport() {
    var e = window, a = 'inner';
    if (!('innerWidth' in window )) {
        a = 'client';
        e = document.documentElement || document.body;
    }
    return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
}

I cant remember where I found this code so i can't give the credit...

Anyway, use the window resize event to check the width like that :

$(window).resize(function(){
    if(viewport().width > x && viewport().width < y){
        //do something
    }
}).trigger('resize');

Comments

1

You can use Paul Irish's MatchMedia.js polyfill to do Javascript media queries but it will not work in IE9 and earlier. Still it's quite useful and you can conditionally handle IE with a less precise method (like $(window).width()).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.