Use jQuery function only on @media screen and (max-width:960px)

Asked

Viewed 3,675 times

4

We know that there are @media queries.

They work with CSS.

But I need to do it with Javascript.

I need bxSlider to work only on @media screen and (max-width:960px).

  • 1

    Post your solution as the answer then (and when the minimum waiting period passes, accept).

2 answers

4


So guys, I did it this way and solved my problem:

jQuery(document).ready(function() {
   if( $(window).width() <= 960){
     jQuery('.img-parceiros').bxSlider({
        nextSelector: '.seta-dir',
        prevSelector: '.seta-esq',
        nextText: '',
        prevText: '',
        auto: false,
        slideWidth: 200,
        minSlides: 2,
        maxSlides: 2,
        pager:false
     });
   }
});
  • 1

    I prefer Diniz’s answer, it’s more specific..

  • In fact, this solution solves half the problem (the max-width), but if the media is not screen the bxSlider will be activated incorrectly.

3

One way that can be done is by using the window.matchMedia.

For example:

if (window.matchMedia('screen and (max-width: 960px)').matches){
  document.write('<script src="../js/bxSlider.js"></script>');
}

Remembering that I did not test, but in theory it should work.

Take a look at this link which should work for other browsers.

  • It doesn’t seem to work... http://jsfiddle.net/mgibsonbr/rs4tK/ (I did something wrong?)

  • Here it worked. Wrote the normal test. Check the browser, as natively only above IE10, among others.

  • Wrote the teste when is under the proposed conditions, but did not write the teste when is not in those conditions?

  • 1

    I found the mistake! The window.matchMedia does not return true or false, but a complex object (MediaQueryList). If you replace your if for window.matchMedia(...).matches works properly there: http://jsfiddle.net/mgibsonbr/rs4tK/1/

  • P.S. Now that I saw that your link also gives the correct solution... : P (I will suggest an edition in your reply then, and give the deserved +1)

  • Valew @mgibsonbr and very good your observation and correction.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.