Home > database >  Jquery media query for 2 devices
Jquery media query for 2 devices

Time:08-04

I made a jquery function for the main desktop screen that add class after scrolling to a certain part of the page.
But is it possible to add two other device specific media query (for iPad and Smartphone) on the function so I can set the scrollTop() > xxx for each device media query ?

$(window).scroll(function () {
    if($(window).scrollTop() > 2700) {
      $('.div_name').addClass('display_on');
    } else {
      $('.div_name').removeClass('display_on');
    }
  });

The other 2 media query I want to add is :

For Ipad :
@media only screen
  and (min-device-width: 601px)
  and (max-device-width: 1112px)
  and (-webkit-min-device-pixel-ratio: 2)

For Smartphone :
@media only screen and (max-device-width: 600px) 

Thanks in advance.

Update 1 :
I've tried to make mix it with a var and made the code as below, but it didn't worked.

  var widthPC = window.matchMedia("(min-width: 768px)");
  var widthTB = window.matchMedia("(min-width: 601px)");
  var widthSP = window.matchMedia("(max-width: 600px)");
  responsive(widthPC);
  responsive(widthTB);
  responsive(widthSP);
  widthPC.addListener(responsive);
  widthTB.addListener(responsive);
  widthSP.addListener(responsive);

  function responsive(widthPC, widthTB, widthSP) {
    if (widthPC.matches) {
      $(window).scrollTop() > 2700 {
        $('.hor_chart_wrap_top').addClass('display_on');
      }
    } else if (widthTB.matches){
      $(window).scrollTop() > 3000 {
        $('.hor_chart_wrap_top').addClass('display_on');
      }
    } else if (widthSP.matches){
      $(window).scrollTop() > 3000 {
        $('.hor_chart_wrap_top').addClass('display_on');
      }
   }
   else {
    $('.hor_chart_wrap_top').removeClass('display_on');
 }};

CodePudding user response:

you can use matchMedia for checking device width

 if (window.matchMedia('(max-width: 600px)').matches) {
        
 }

CodePudding user response:

I end up making a code below and it works ! :

  $(window).scroll(function(){
    if ($(this).scrollTop() > 3200 && $(window).width() >= 1112) {
      $('.chart_1').addClass('display_on');
     }
     else if ($(this).scrollTop() > 2200 && $(window).width() >= 601 && $(window).width() <= 1112) {
      $('.chart_1').addClass('display_on');
     }
     else if ($(this).scrollTop() > 5000 && $(window).width() < 600) {
      $('.chart_1').addClass('display_on');
     }
     else {
      $('.chart_1').removeClass('display_on');
     }
  });
  • Related