0
        $(window).scroll(function() {
        if (($(this).scrollTop() > 102) && ($(window).width() > 768)) {  
            $('header').addClass("header-scroll");
          }
          else{
            $('header').removeClass("header-scroll");
          }
        });

I'm trying to make code that adds classes to the header on a page when it's scrolled on desktop only. how to do it right?

mx928
  • 1
  • 1
  • I checked your code that is working well. I think your issue caused from Jquery library import missing or version issue. I will upload code that working on my side. – Dev Conductor Aug 28 '23 at 02:18

3 Answers3

0

Here is the code you can use:

$(window).scroll(function() {
    if ($(window).width() > 768) {
        if ($(this).scrollTop() > 102) {
            $('header').addClass("header-scroll");
        } else {
            $('header').removeClass("header-scroll");
        }
    }
});
0

Reference this answer : How to detect a mobile device using jQuery

you can use this code:

if( !/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
    $(window).scroll(function() {
        if ($(this).scrollTop() > 102 && $(window).width() > 768) {  
            $('header').addClass("header-scroll");
        } else {
            $('header').removeClass("header-scroll");
        }
    });
}
sym
  • 36
  • 3
0
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
    
</head>
<body>
<header>
    <h1>This is header</h1>
</header>
<div style="height: 500px; background-color: blue;">
    Scroll view 1
</div>
<div style="height: 500px; background-color: yellow;">
    Scroll view 1
</div>
<script type="text/javascript">
    $(window).scroll(function() {
    if (($(this).scrollTop() > 102) && ($(window).width() > 768)) {  
        $('header').addClass("header-scroll");
      }
      else{
        $('header').removeClass("header-scroll");
      }
    });
</script>
</body>
</html>
Dev Conductor
  • 179
  • 2
  • 9