Search code examples
jquerymedia-queriesresponsive

Need to have a javascript function only work on desktop screens and disable on mobile


I'm running a function in Javascript that I need to only work on desktop screens (anything larger than 1000px wide in this case) and I need some help please.

Here is my function:

 $(document).ready(function () {
     $(window).scroll(function () {
         if ($(document).scrollTop() > 1650) {
             $("#table-top").addClass("scrolled");} 
         else {$("#table-top").removeClass("scrolled");}
     });
 });

So here is what the background story is.

For our company website, we have a plans and pricing page, with a large table of the features of each pricing option, its a very long table, you have to scroll for a while to view it all. On this page I already have a sticky navigation bar at the top of the screen, and we're keeping it there. Everything about this website is already mobile responsive, and working just fine, until my boss asked me to add a second sticky horizontal bar, just like this page here (https://www.caspio.com/pricing/) where as you scroll down the page, the pricing plan header box sticks at the top of the screen as you scroll down.

I was able to do this, woo hoo! (patting myself on the back as a junior developer who is new to the game) and it looks great, and as the user scrolls about 1650px down the page, the new bar pops in, and it looks smooth, but then I tested the site in mobile, and now it looks terrible, on mobile and throws off how everything looks in mobile, so if I could just simply write some .js to have this function only activate while in desktop mode only (screens larger than 1000 px) that would save my butt!

Thank you for any advice or helpful suggestions!


Solution

  •     if (window.innerWidth > 1000) {   
    
             $(document).ready(function () {
                 $(window).scroll(function () {
                     if ($(document).scrollTop() > 1650) {
                         $("#table-top").addClass("scrolled");} 
                     else {$("#table-top").removeClass("scrolled");}
                 });
             }); 
    }
    

    Something like this should work?