Home > Blockchain >  JQuery scrollTop function for adjusting css not working
JQuery scrollTop function for adjusting css not working

Time:12-09

I'm trying to shrink the margin-top value on scroll since I'm using an announcement bar that disappears on scroll.

Here is the script with the CSS I'm currently using, it's all in the theme.liquid file (I'm using Shopify):

<script
      src="https://code.jquery.com/jquery-3.6.0.min.js"
      integrity="sha256-/xUj 3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
      crossorigin="anonymous"></script>
    <script>
      $(window).scroll(function(){
        if ($(this).scrollTop() > 50) {
           $('#christmas-header-image-pc').addClass('christmas-header-image-margin');
        } else {
           $('#christmas-header-image-pc').removeClass('christmas-header-image-margin');
        }
    });
</script>

      <style>
      #christmas-header-image-pc {
          top:0!important;
          margin-top:120px;
          z-index:5;
          height:auto;
          position:fixed;
        }
      .christmas-header-image-margin {
          margin-top:55px;
      }
      </style>

      <img id="christmas-header-image-pc" src="https://cdn.shopify.com/s/files/1/0568/1191/3367/files/christmas-header-decoration.svg?v=1638965731">

I can't seem to get it working. The value needs to go from 120px to 55px.

On the frontend this is happening right now: enter image description here

This is happening when I scroll: enter image description here

Any help is appreciated! Thanks in advance.

CodePudding user response:

it looks like your jQuery is working just fine, the new class is being added to the image after the scrollTop is above 50.

Your issue has to do with CSS Specificity, add the ID to the new class ruleset like this:

#christmas-header-image-pc.christmas-header-image-margin {
  margin-top:55px;
}

Here's a great article by MDN about the topic of specificity.

Specificity is the means by which browsers decide which CSS property values are the most relevant to an element and, therefore, will be applied. Specificity is based on the matching rules which are composed of different sorts of CSS selectors.

jQuery(window).scroll(function(){
  if (jQuery(this).scrollTop() > 50) {
     jQuery('#christmas-header-image-pc').addClass('christmas-header-image-margin');
  } else {
     jQuery('#christmas-header-image-pc').removeClass('christmas-header-image-margin');
  }
});
section {
  min-height:2000px;
}

#christmas-header-image-pc {
    top:0!important;
    margin-top:120px;
    z-index:5;
    height:auto;
    position:fixed;
    transition:300ms;
  }
#christmas-header-image-pc.christmas-header-image-margin {
    margin-top:55px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section>
  <img id="christmas-header-image-pc" src="https://cdn.shopify.com/s/files/1/0568/1191/3367/files/christmas-header-decoration.svg?v=1638965731">
</section>

  • Related