Change image as user scrolls up and down with Javascrip

I have two images (a closed box and an open box)you can view the working animation I am trying to replicate on this site. The image changes when the user scrolls up and down the page. How would I create this effect?

I have tried the code below but that is not working for me. Where am I going wrong?

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Box Animation</title>
</head>
<body>
  <style>
      .center {
      display: block;
      margin-left: auto;
      margin-right: auto;
      width: 65%
  </style>
  <div id="product_open_closed">
    <img src="https://supamama.co.za/img/product/open.png" height="250" width="370" class="center" />
  </div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    var $cover_img = $("#product_open_close");
    var top = 0;
    var switchx = 10;
    
    $(document).scroll(function(event) {
      top += 1;
      if (top >= switchx) {
        $cover_img.attr('src', 'wp-content/uploads/2021/02/open.png');
        if (top >= (switchx * 2))
          top = 0;
      } else {
        $cover_img.attr('src', 'wp-content/uploads/2021/02/closed.png');
      }
    });
  </script>
</body>
</html>

Answer

There are a few issues here:

  1. You’re selecting the wrong ID. You want $("#product_open_closed"); and not $("#product_open_close");

  2. You’re changing the src of the div tag and not the img tag, so the image itself won’t be changing. You’ll want to remove the div tag and add the id="product_open_closed" to the img tag instead.

  3. In the window, top is already a global variable that references window.top. So, since you’re not in a separate js file, you’ll want to rename top to something else, e.g. offset.

  4. With ES6, you’ll want to avoid using var now and use let or const instead.

  5. Generally, you want to split different scripts into different script tags. So, if you’re loading jQuery in one script tag, then you shouldn’t put any js inside of that script tag and should instead create a separate one.

Final code:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Box Animation</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>

    <img src="https://supamama.co.za/img/product/open.png" 
     height="250" 
     width="370" 
     class="center" 
     id="product_open_closed"
    />

<script>
    let $cover_img = $("#product_open_closed");
    let offset = 0;
    let switchx = 10;
    
    $(document).scroll(function(event) {
      offset += 1;
      if (offset >= switchx) {
        $cover_img.attr('src', 'https://supamama.co.za/img/product/open.png');
        if (offset >= (switchx * 2))
          offset = 0;
      } else {
        $cover_img.attr('src', 'https://supamama.co.za/img/product/closed.png');
      }
    });
</script>
</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *