Scrolling is causing elements to move horizontally, leading to a scroll effect

I have been working on a website for a company and managed to make an element move as you scroll using jQuery. However, I've run into an issue where the movement of the element is causing excessive horizontal scrolling because it keeps moving further down as you scroll.

Is there a way to restrict the scrolling once the element goes out of view? Or perhaps set a maximum distance that it can move? I feel like I've been staring at this for too long without finding a solution.

$(function () {
    var window_width = $(window).width() - $('#square_scroll01').width();
    
    var document_height = $(document).height() - $(window).height();
    
    $(window).scroll(function () {
        var scroll_position = $(window).scrollTop();
        var object_position_left = window_width * ((scroll_position / document_height) * 3);
        $('#square_scroll01').css({
            'left': object_position_left
        });
    });
});
.hero {
    background: url(https://source.unsplash.com/5U_28ojjgms/1600x900) center center no-repeat;
    background-size: cover;
    height: 100vh;
    width: 100vw;
    position: relative;
}

.hero-content {
    position: absolute;
    top: 20%;
}

.p1 {
  color: #fff;
}

.p2 {
  color: #000;
}

#square_scroll01 {
    position: absolute;
    left: 9.5%;
    bottom: -1.8%;
    height: 35px;
    width: 35px;
    border-radius:5px;
    background: #7AC143;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="hero">
    <div id="square_scroll01">
    </div>
</section>
View JSFiddle here

Answer №1

  • Implement overflow-x: hidden; on either the body element or a known ancestor for better performance.
  • To smoothly animate your element, consider using transform: translate instead of properties like left, which can be GPU accelerated and less choppy.

jQuery($ => { // When DOM is ready and $ is in scope

  const $square = $('#square_scroll01'); // Store elements to avoid redundancy
  const availWidth = $(window).width() - $square.width();
  const docHeight = $(document).height() - $(window).height();

  $(window).on("scroll", function() {
    const scrollTop = $(window).scrollTop();
    const posX = availWidth * scrollTop / docHeight * 3;
    $square.css({
      transform: `translateX(${posX}px)`
    });
  });

});
/* QuickReset */

* {
  margin: 0;
  box-sizing: border-box;
}

body {
  overflow-x: hidden;
}

.hero {
  background: url(https://source.unsplash.com/5U_28ojjgms/1600x900) no-repeat center center / cover;
  height: 100vh;
  /*width: 100vw; /* UNNECESSARY */
  position: relative;
  color: #fff;
}

#square_scroll01 {
  position: absolute;
  left: 9.5%;
  bottom: -1.8%;
  height: 35px;
  width: 35px;
  border-radius: 5px;
  background: #7AC143;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

<section class="hero container-lg">
  <div class="hero-content col-lg-6">
    <h1 class="display-5 fw-bold text-light">Creating boundless communication together</h1>
    <p class="p1" style="height: 200vh;">Just some tall content... Scroll down...</p>
    <div class="justify-content-md-start">
      <button type="button" class="btn btn-primary text-light btn-md px-4 me-md-2">Contact us</button>
    </div>
  </div>
  <div id="square_scroll01"></div>
</section>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

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

Carry out a series of functions

I'm experimenting with a combination of d3.js and jQuery for my visualization project. I am attempting to place 3 functions into an array and then run them sequentially, however, it seems like I might be doing something wrong because when I click "pla ...

Error: PHP syntax error occurred due to unexpected double-quote mark

As a beginner in php, I've been encountering an error in my code echo "<a href=\"PHadmin_deletePatient.php?id=<?php echo $row["PatientID"]; ?>\" class='delete' title='Delete' data-toggle= ...

Achieving consistent height for Bootstrap5 columns: A simple guide

I'm currently utilizing Bootstrap5 and I am interested in adjusting the height of these two columns to be similar. Is there a way to achieve this? Below is the code snippet: <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email ...

how to show an error in a modal window when encountering an error

Using Blazor and Blazorstrap, typically when the server disconnects, an "Error" message is displayed. However, with the BsModal from Blazorstrap, it appears in the background layer, making it unresponsive. How can this be fixed? Is it possible to close the ...

Presentation: Positioning Next Buttons Beside Slide Images While Maintaining Responsiveness

I am facing a challenge with my slideshow project. The slideshow consists of images and text on each slide, along with previous and next buttons that are aligned within the parent container. I am trying to align these buttons at the midpoint of each image ...

What is the best way to prevent my images from resizing in a Bootstrap 4 carousel?

I am working on a website where users can upload images of various sizes. These images are then displayed in a Bootstrap 4 carousel. I want to ensure that the carousel maintains a consistent dimension across different screen sizes without changing the widt ...

Unable to view indicators and slides are not transitioning in Bootstrap carousel

I am in the process of developing a website with bootstrap, but I am encountering issues with the carousel feature. Despite copying the code directly from their official page, the carousel remains non-functional. The indicators are missing, and the slides ...

Tips for preserving login status even after the browser is shut down with the help of JavaScript

I need help with maintaining a user session in my chat application even when the browser is closed. After users log in for the first time, I want their credentials to be remembered by the browser (I'm currently using local storage). How can I ensure ...

Having trouble locating the accurate URL for the deployed server in Web Core API

I am encountering a perplexing issue when attempting to access my deployed Web API Core from AJAX, as I consistently receive a 404 error. Although I can successfully make calls to the API from C# code, the jQuery code below seems to be causing trouble: va ...

Modify the input based on the chosen option operation

I am working on a project where I have 3 select elements and when a user selects an option, the associated value should be displayed in an input field. I am trying to use a single function for these 3 selects, but I am facing some issues. Here is the HTML ...

Is it possible to apply CSS based on a component's displayName?

Are you a CSS pro? I'm attempting to apply a class that will make all descendants of an element read-only, but for some reason the style isn't being applied as expected: #ComponentDisplayName * { -webkit-user-select: text; -moz-user-sel ...

Enrolling JavaScript documents and connected inline programming

I need a solution for dealing with two arrays. The first array consists of URLs pointing to JavaScript files that I want to register using $.getScript(url); Next, the second array contains inline JavaScript commands that should be registered with $("html ...

Background and border presentation issues arising from CSS conflict

While working on a webpage, I encountered a design conflict within a div that contains a group of other div elements. The current appearance can be seen at , and the desired look is shown in the image here: enter image description here ...

Re-executing PHP script using AJAX on the existing webpage

I am facing a rather intricate issue. Currently, I am in the process of constructing a page that searches tags in a MySQL table and displays results without any reloading or redirection. The tags are user-input and managed using JavaScript. Let me outline ...

I am seeking advice on how to incorporate JavaScript to adjust slider values and add numerical values or prices. Any suggestions would

Seeking assistance with a unique project: I am currently developing a calculator that allows users to utilize sliders to select the best option for themselves across various categories. My experience with JavaScript is limited, so I decided to reach out h ...

Is it possible to use Google to search for specific HTML elements, or is there another method to identify elements without needing to provide the URL?

Can Google be used to search for specific elements? Is there a way to identify elements without needing the URL? An extensive search to locate elements. Example: I am trying to find websites that contain this particular class: .main-category-box.catego ...

Disable functionality not functioning properly on button attribute

I've created a demo on JSFiddle here: http://jsfiddle.net/qJdaA/2/. The goal of this code is to disable the button with the ID #monitor if no checkboxes are checked. var checked = $('#status_table tr [id^="monitor_"]:checked'); if (checked. ...

Having trouble deciding between JSON, XML, or using a database?

As I work on developing an app that involves sending an id and receiving a JSON node from PHP, I am considering the best approach for storing my data. Should I keep it as a static PHP array as shown in the code below, or should I save the data to an exte ...

What is the best way to transfer floating point input values from one page to another for later retrieval?

Is there a way to send floating point values to another page? I tried sending a floating point value in an AJAX request, but the receiving page only gets an integer value. <div class="form-group"> <label for="" class="col-sm-4 control-label"> ...

Issues with jQuery functionality occurring when trying to display or hide div contents on dynamically loaded AJAX content

I have encountered an issue while working on a project that involves showing or hiding a div based on the selection of a drop down value. The show/hide functionality works perfectly when implemented on the same page, but it fails when I try to do the same ...