skip to Main Content

I want to create an action using HTML, CSS and JS, when you scroll horizontally on a div.

This code which I found on w3Schools is what I was looking for, but I can not modify it to accept horizontal scroll. Basically it needs to indicate which image is on screen (1 or 2) using lets say dots.

window.onscroll = function() {
  myFunction()
};

function myFunction() {
  if (document.documentElement.scrollTop > 50) {
    document.getElementById("myP").className = "test";
  } else {
    document.getElementById("myP").className = "";
  }
}
body {
  font-size: 20px;
  height: 1500px;
}

#myP {
  position: fixed;
}

.test {
  background-color: yellow;
}
<h1>The onscroll Event</h1>

<p id="myP">
  If you scroll 50 pixels down from the top of this page, the class "test" is added to this paragraph. Scroll up again to remove the class.
</p>

I tried to modify the code from previous link and some others, but without success. This code seem to be the closest to what I need.

3

Answers


  1. To make this work horizontally make the page content wider than the viewport, in the example I simply set its width to 5000px, and change scrollTop in the JS logic to scrollLeft.

    Also note that the code quality from W3Schools is very rarely of good quality. It’s for this reason I would strongly suggest you avoid them and use a better resource, such as MDN.

    To improve the quality of the code in your example you can avoid using onscroll or any of the other event properties. Use addEventListener() instead. In addition use the classList collection to add/remove/toggle classes on elements.

    const p = document.querySelector('#myP');
    
    window.addEventListener('scroll', () => {
      p.classList.toggle('test', document.documentElement.scrollLeft > 50) 
    });
    body {
      font-size: 20px;
      width: 5000px;
    }
    
    #myP {
      position: fixed;
    }
    
    .test {
      background-color: yellow;
    }
    <h1>The onscroll Event</h1>
    
    <p id="myP">
      If you scroll 50 pixels from the left of this page, the class "test" is added to this paragraph. Scroll right again to remove the class.
    </p>
    Login or Signup to reply.
  2. To highlight the text when horizontally scrolling, you firstly adjust the width:

    <body style="font-size:20px;width:1500px">
    

    This makes sure there is enough space to scroll horizontally.

    After you have done that, to apply the effect when scrolling, instead of scrollUp you use scrollLeft like this:

      if (document.documentElement.scrollLeft > 50) {
    

    This should highlight the text when scrolling horizontally 50 pixels.

    Login or Signup to reply.
  3. to achieve horizontal scrolling detection and indicate which image is currently on the screen, you’ll need to make a few adjustments to your code

    window.addEventListener('scroll', function() {
        var scrollPosition = window.scrollX; // Horizontal scroll position
    
        // Calculate which image is currently in view
        var containerWidth = document.getElementById('container').offsetWidth;
        var imageIndex = Math.floor(scrollPosition / containerWidth);
    
        // Update dots to indicate current image
        var dots = document.querySelectorAll('.dot');
        dots.forEach(function(dot, index) {
          if (index === imageIndex) {
            dot.classList.add('active');
          } else {
            dot.classList.remove('active');
          }
        });
      });
    
      // Add dots for each image
      var container = document.getElementById('container');
      var numImages = container.children.length;
      var dotsContainer = document.getElementById('dots');
      for (var i = 0; i < numImages; i++) {
        var dot = document.createElement('span');
        dot.classList.add('dot');
        dotsContainer.appendChild(dot);
      }
     body {
        font-size: 20px;
        height: 100vh;
        overflow-x: hidden; /* Hide vertical scrollbar */
        overflow-y: hidden; /* Hide horizontal scrollbar */
        margin: 0;
        padding: 0;
      }
    
      #container {
        width: 200vw; /* Make the container twice as wide as the viewport */
        white-space: nowrap; /* Prevent line breaks */
        font-size: 0; /* Remove whitespace between inline-block elements */
      }
    
      .image {
        display: inline-block;
        width: 100vw; /* Each image takes the full width of the viewport */
        height: 100vh;
        background-size: cover;
        background-position: center;
      }
    
      .dot {
        display: inline-block;
        width: 10px;
        height: 10px;
        border-radius: 50%;
        background-color: gray;
        margin-right: 5px;
      }
    
      .dot.active {
        background-color: yellow;
      }
    <div id="container">
      <div class="image" style="background-image: url('image1.jpg');"></div>
      <div class="image" style="background-image: url('image2.jpg');"></div>
    </div>
    
    <div id="dots"></div>

    In this code:

    • Two images are placed horizontally within a container.
    • Each image takes the full width of the viewport, and the container is made twice as wide as the viewport to accommodate both images.
    • The JavaScript code calculates the current scroll position (scrollPosition) and determines which image is currently in view by dividing the scroll position by the container width.
    • Dots are added dynamically to indicate the current image, and their
      color changes to yellow when the corresponding image is in view.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search