Using JQuery for Smooth Image Scrolling

My goal is to create a scrolling function for images similar to the one on this website bethellery.com. Currently, my code is somewhat functional, but I am facing a major issue: the size of the scrolling bar is almost as large as my div, making it difficult to scroll effectively.

Below is the HTML structure:

<div id="container">
    <div class="img-inner" id="img-1" style="display: block" >
        <img class="img" src="src-1" alt="alt-1" />      
    </div>

    <div class="img-inner" id="img-2" style="display: none" >
        <img class="img" src="src-2" alt="alt-2" />      
    </div>

    <div class="img-inner" id="img-3" style="display: none" >
        <img class="img" src="src-3" alt="alt-3" />      
    </div>

    <div class="img-inner" id="img-4" style="display: none" >
        <img class="img" src="src-4" alt="alt-4" />      
    </div>
</div>

Here is the corresponding CSS:

html, body {
    margin: 0px;
    padding: 0px;
    height: 100%;
}

#container {
    height: 100%;
    width: 50%;
    overflow-y: auto;
}

.img-inner{
    height: 100%;
    width: 100%;
}

.img {
    height: 100%;
    width: 100%;
}

And here is the used JavaScript:

var lastScrollTop = 0;
var x = 1;

$('#container').scroll(function(event){
    var st = $(this).scrollTop();

    if(st > lastScrollTop){
        //downscroll code       
        document.getElementById('img-'+x).style.display = "none";
        
        if((x+1) !== 4){
            x=x+1;
        }
        document.getElementById('img-'+x).style.display = "block";
    }
    else{
        document.getElementById('img-'+x).style.display = "none";
        if((x-1) !== 0){
            x=x-1;
        }
        document.getElementById('img-'+x).style.display = "block";
    }
    lastScrollTop = st;
});

I suspect that due to the display styles of the div being none, the scrolling function doesn't properly recognize the flow under the first image.

In contrast, the site mentioned above adjusts the scroll bar size based on the number of images within the div.

Thank you and have a wonderful day!

Answer №1

The issue lies in the fact that when using display: none;, an element's display is turned off, resulting in no impact on the layout (according to MDN). This means any calculations involving it will simply not be considered.

This can be seen in action with the JSFiddle example (based on your code) - by setting two images to display: block;, the scrollbar becomes visible.

To address this, consider using visibility: hidden; instead, as illustrated in this demonstration. Unlike display: none;, visibility maintains the space occupied by an element while keeping it hidden. Its behavior is similar to that of opacity.

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

Retrieve the second occurrence of a regular expression match

I'm currently working on extracting the second occurrence in a regular expression string. Let's consider a domain name: https://regexrocks.com/my/socks/off We want to replace everything after .com $this.val($this.val().replace(/(([^.]*.)[^]?. ...

Utilize a component's CSS styles by inheriting them and applying them to another component

I have created custom styles for an object as shown below: form#sign_in{ position:relative; margin:85px auto 50px auto; width:455px; background:#fff; border:#dfdfdf 1px solid; border-radius:5px; -moz-border-radius:5px; -web ...

Calculate and retrieve the result from the event handling function

I need to capture a returned value and store it in a variable within an event handler function. Below is a sample code snippet demonstrating this: var xhr = new XMLHttpRequest(); function getData(e) { if (xhr.readyState === 4) { if (xhr.s ...

Is there a way to determine if an array includes an integer value?

I've been attempting to iterate through an array to verify if it includes an integer, but I'm struggling to make it work and I'm not sure why. Is it necessary to use the map method? Here is my code snippet: let words = ['Dog', & ...

Error message: ReactJs is unable to read the property 'map' as it is undefined

After making an axios get request to a Yelp API, I successfully retrieved the data and logged 20 results in an object array. However, when attempting to map through the results, I encountered two errors in my console: app.js:53912 Uncaught TypeError: Can ...

Website search bar - easily find what you're looking for

I've tested this code and it works well on the basintap page. However, I'm interested to find out how I can search for something when I'm on a different page instead? <?php $query = $_GET['query']; $min_length = 2; if(strlen($ ...

A guide on customizing column names in MUI Datatables through object keys

I'm currently facing an issue where I need to set the name of a column in MUI Datatables using an object key. Specifically, I want to set one of the column names with the first element of children.childName so that it displays a list of child names, b ...

How can I retrieve the class of the parent element by referencing the child id in jQuery?

I want to trigger an alert on click from the child id <th id="first"> to the table(parent) class. alert($(this).parent('tr').attr('class')); This code helped me to get the class of the <tr>. However, when I try to get the ...

Apply a CSS class upon clicking the button

How can I use jQuery to add a class to my "infoBlock" and style its elements accordingly? I have an infoBlock but need assistance with adding a new class. li { list-style-type: none; } .infoBlock { display: block; width: 520px; height: 280px; back ...

How to update the first element of an array to 1 using Javascript

I am looking for a way to display a list of songs from an array in ascending order, starting from 1 instead of 0. Here is the current result: songs list Instead of starting from zero, I want to begin counting from one. The current output that I have achi ...

Changing the position of elements based on screen resolution for Desktop and Mobile

I'm working on a page with a sidebar that contains elements on desktop. When viewed on mobile, the sidebar moves under the main page. However, I would like those elements to be displayed above the main page on mobile, similar to this: Any suggestions ...

Angular2+ does not return any elements when using .getElementsByClassName() even if they are present

I have a question that seems simple, but I can't seem to find the answer anywhere. I've looked through past questions but still haven't found a solution... In my Angular template, there is a large amount of text inside a div, and some parts ...

scrollable material ui chips list with navigation arrows

I'm attempting to create a unique scrollable chips array using Material UI version 4 (not version 5). Previous examples demonstrate similar functionality: View Demo Code I would like to update the scrolling bar of this component to include l ...

Utilize/Absolve/Add a Prefix to angular material scss styles

Issue I am facing a challenge with integrating angular material SCSS into my application. I want to ensure that these styles are isolated and scoped specifically for my application, as it will be embedded within a larger monolith. The goal is to prevent a ...

Begin Leaflet with JQuery UI Slider set to a predefined value

I have integrated the LeafletSlider library into my project to slide through multiple layers with different timestamps in Leaflet. My goal is to initialize the slider at the timestamp closest to the current time. In SliderControl.js, I made the following ...

Can someone show me the JavaScript code to split a string at every instance of ' '?

Hey there! I have a question about manipulating strings. Take a look at this example: var string = '"In Another World" "Magic Books"' I want to create an array that contains every name within the [""]. How can I ach ...

The extension's script initiates without waiting for the entire page to finish loading

Recently, I have embarked on developing a chrome extension that requires waiting for a YouTube page to fully load before inserting a button into the existing code. Despite using getElementById() to locate the element, the script often completes execution b ...

What is the method for including the `meta:redirect` or `<meta http-equiv="refresh" content="0; url=http://example.com" />` in the metadata object for Next.js version 13?

In order to redirect users from one of my pages, I previously utilized the redirect metatag. However, I am unable to locate similar options within the metadata API in Next.js 13 for the appRouter. ...

What could be causing the state of a child component to continuously reset?

I have a complex system of React components designed for fetching an embed from a music service API. This includes a higher-order component that interacts with the API to load the embed data. The issue I am facing is that my lowest-level child component is ...

Exploring ways to find a particular value within an array of objects

Struggling to make my code render the data upon searching for a specific value. I attempted using a for loop, but I keep encountering an 'unexpected token' error. Is there a more effective way to accomplish this task? While this may seem like a s ...