skip to Main Content
        $(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?

3

Answers


  1. 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");
            }
        }
    });
    
    Login or Signup to reply.
  2. 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");
            }
        });
    }
    
    Login or Signup to reply.
  3. <!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>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search