Scrolling horizontally using jQuery and CSS

I have been experimenting with creating a horizontal scrolling page that moves to the right when scrolling down and to the left when scrolling up. Here is the current code:

HTML

<div class="scroll-sections">
            <section id="section-1">
                <div class="container">
                    <div class="row">
                        <div class="col-md-12">
                            <h1>Section 1</h1>
                        </div>
                    </div>
                </div>
            </section>
            <section id="section-2">
                <div class="container">
                    <div class="row">
                        <div class="col-md-12">
                            <h1>Section 2</h1>
                        </div>
                    </div>
                </div>
            </section>
            <section id="section-3">
                <div class="container">
                    <div class="row">
                        <div class="col-md-12">
                            <h1>Section 3</h1>
                        </div>
                    </div>
                </div>
            </section>
            <section id="section-4">
                <div class="container">
                    <div class="row">
                        <div class="col-md-12">
                            <h1>Section 4</h1>
                        </div>
                    </div>
                </div>
            </section>
            <section id="section-5">
                <div class="container">
                    <div class="row">
                        <div class="col-md-12">
                            <h1>Section 5</h1>
                        </div>
                    </div>
                </div>
            </section>
        </div>

CSS

section {
    height: 100vh;
    padding-left: 125px;
    display: inline-block;
    z-index: 2;
    overflow: visible;
    white-space: nowrap;
}

.scroll-sections {
    padding: 0;
    list-style: none;
    font-size: 0;
    margin: 0;
    white-space: nowrap;
    height: 100%;
    position: relative;
    overflow: visible;
}

jQuery

$(document).ready(function(){
  var pos = 0;
  $(".scroll-sections").bind('mousewheel DOMMouseScroll', function(event) {
    if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) {
      pos = pos + 50;

    } else {

      pos = pos - 50;
    }
    $(".scroll-sections").css({left: pos});
    return false;
  });

});

The current setup works, but it lacks smoothness. Additionally, it encounters problems when reaching the ends of the sections. I am aiming for a smooth scrolling experience similar to this website:

Any suggestions or assistance would be greatly appreciated.

UPDATE

I managed to achieve smoother scrolling with this adjusted code:

$(document).ready(function(){
  var pos = 0;
  $(".scroll-sections").bind('mousewheel DOMMouseScroll', function(event) {
    if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) {
      pos = pos + 10;

    } else {

      pos = pos - 10;
    }
    $(".scroll-sections").css({left: pos});
    return false;
  });

});

However, the issue of getting stuck at the beginning and end of sections persists. When scrolling back to the beginning of section-1, it requires scrolling down to resume smooth scrolling. Similarly, when reaching the end of section-5, the scrolling continues. Any further advice on resolving these issues is welcome.

Answer №1

$(document).ready(function(){
    var pos = 0;
    var lastElement = $(".scroll-sections").children().last();
    var maxScroll = $(".scroll-sections").width()  - (lastElement.offset().left + lastElement.outerWidth());
    
    $(".scroll-sections").on('wheel', function(event) {
        pos = pos + (event.originalEvent.wheelDelta/3);
        if(pos > 0 ){
            pos = 0;
        } 
        if(pos < maxScroll){
            pos= maxScroll;
        }
        $(".scroll-sections").css({'transform': 'translateX(' + pos + 'px)'});
        return false;
    });
  
  });
html, body{
    margin: 0px;
    overflow: hidden;
}
section {
    height: 99vh;
    display: inline-block;
    width: 33.3%;
    border: 1px solid red;
    overflow: visible;
}

.scroll-sections {
    white-space: nowrap;
    height: 100%;
    overflow: visible;
    transition-duration: 0.5s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="scroll-sections">
    <section id="section-1">
        <div class="container">
            <div class="row">
                <div class="col-md-12">
                    <h1>Section 1</h1>
                </div>
            </div>
        </div>
    </section>
    <section id="section-2">
        <div class="container">
            <div class="row">
                <div class="col-md-12">
                    <h1>Section 2</h1>
                </div>
            </div>
        </div>
    </section>
    <section id="section-3">
        <div class="container">
            <div class="row">
                <div class="col-md-12">
                    <h1>Section 3</h1>
                </div>
            </div>
        </div>
    </section>
    <section id="section-4">
        <div class="container">
            <div class="row">
                <div class="col-md-12">
                    <h1>Section 4</h1>
                </div>
            </div>
        </div>
    </section>
    <section id="section-5">
        <div class="container">
            <div class="row">
                <div class="col-md-12">
                    <h1>Section 5</h1>
                </div>
            </div>
        </div>
    </section>
</div>

Explore the provided demo above. It includes a horizontal scroll feature which can be customized as needed.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discord bot in Node.js, Remove old embed message upon receiving a slash command

My bot is programmed to send an embed message whenever it receives a /xyz command, and the code looks something like this: client.on("interactionCreate", async (interaction) => { if (!interaction.isCommand()) return; const ...

Encountering error when using require() with Firebase in Express

I am facing an issue with my Express application while attempting to connect it to Firebase. Currently, my console is showing an error message: C:\Users\Tyler\Desktop\Dev\food-bank\app.cjs:19 const firebase = initializeApp(fi ...

Executing an Ajax callback function to navigate to a different page

I must handle ajax errors globally by capturing 901 error codes in my header.jsp. There is an error message displayed in the browser console: GET https://localhost:8443/SSApp/Pan/report?&vessel…namax%20Tanker%20Pool%20Limited&rptTitle=Activit ...

Unable to persist cookies while utilizing npm's request library

I'm currently working on setting up a local environment where I'm attempting to log into a service. In the client side, I'm using the 'request' library, and on the service side, I'm utilizing Express and express-session. Whil ...

Increase the object name in localStorage to save information entered in input fields

For testing purposes only - do not use for production. I am experimenting with storing data from 3 different input fields (text and numbers) in localStorage. My goal is to have the values increment every time the form is submitted. However, I am encounte ...

My function doesn't seem to be cooperating with async/await

const initialState={ isLoggedIn: false, userData: null, } function App() { const [state, setState]= useState(initialState) useEffect(()=>{ async function fetchUserData(){ await initializeUserInfo({state, setState}) // encountering an ...

Display Text Aligned in the Middle Beside Website's Logo

Newbie to HTML and CSS here! I'm attempting to achieve a design similar to this: https://i.sstatic.net/HyiP3.jpg Below is my code snippet: <div id="topbar"> <div class="image"> <img src="images/ghwlogo.png"> </ ...

The top margin is experiencing issues and is not functioning correctly

I'm struggling to identify the problem with this script: http://jsfiddle.net/AKB3d/ #second { margin-top:50px; ... } My goal is to have the yellow box positioned 50px below the top border of the right box. However, every time I add margin-top to ...

What exactly is the hashtag text and what is the best way to eliminate it?

While working with Bootstrap, I encountered a strange issue where an unknown element with the id of "text" appeared out of nowhere. When I view the page in my browser, there are #text elements appearing between each <li> elements. Upon inspecting the ...

The accordion's height will expand on its own when one of the accordions in the same row is

Whenever an accordion expands in the same row in MUI, the height of the accordion will automatically increase. See below for the code snippet: {[1,2,3,4,5].map((i)=> <Accordion style={{backgroundColor: '#F9F9F9&ap ...

Vue.js - Capturing a scroll event within a vuetify v-dialog component

Currently, I am working on a JavaScript project that involves implementing a 'scroll-to-top' button within a Vuetify v-dialog component. The button should only appear after the user has scrolled down by 20px along the y-axis. Within the v-dialog, ...

Prevent JavaScript from being entered into the form

I'm currently developing an "HTML editor" for one of my webpages. Right now, I want to ensure that the editor only allows input of HTML and CSS elements without any Javascript (or Jquery). I've been attempting to prevent the use of <script> ...

Sending the questionId and user's answer to a controller in ASP.NET Core using AJAX is a common task. The process involves

I am attempting to store questionIds and user responses in a class that includes dictionaries using ajax. Below is the ViewModel class: public class AnswersVM { public List<Dictionary<int, string>> group { get; set; } public List<Dictio ...

Personalize the error message for throwing an exception in JavaScript

I've been working on customizing error messages for exceptions thrown in JavaScript. Despite my best efforts, I have not been successful so far. I'm currently attempting the following code snippet but it's not functioning as expected: f ...

Obtain an array containing only unique values from a combination of arrays

Is there a simple way or plugin that can help me combine values from multiple arrays into one new array without duplicates? var x = { "12": [3, 4], "13": [3], "14": [1, 4] }; The resulting array should only contain unique values: [1, 3, 4]; ...

Tips on maintaining the original text hues that were established using setForeground() when a QTableWidgetItem is picked

Issue at Hand: Currently, when the first row is selected as shown in Figure 2 below, all text colors are changed to black, instead of maintaining their original style displayed in Figure 1. Is there a way to retain the original colors when a row is selec ...

What is the best way to flip the pentagon shape made with CSS?

I need assistance in creating a downward-pointing pentagon shape. However, I am unsure of how to define the points on the shape. #pentagon { margin:70px 0 5px 20px; position: relative; width: 110px; border-width: 100px 36px 0; border-style: solid; ...

What makes Twitter Bootstrap special that modal events function in JQuery but not in pure JavaScript?

When working with the Twitter Bootstrap modal dialog, there is a set of events that can be utilized with callbacks. For instance, in jQuery: $(modalID).on('hidden.bs.modal', function (e) { console.log("hidden.bs.modal"); }); I ...

What steps can I take to avoid unnecessary re-rendering of a variable that is not utilized in the HTML of my vue.js component?

I am currently in the process of replicating a real-life example of my code. In the actual code, this line represents a component that will continuously fetch an endpoint every few seconds, retrieving a random array of length "n", encapsulated wi ...

What is the purpose of the JSON.stringify() function converting special characters?

I attempted the following code snippet: console.log(JSON.stringify({ test: "\u30FCabc" })); The result is as follows: '{"test":"ーabc"}' We are aware that primarily, the JSON.stringify() method converts a Jav ...