Direction of Scrolling

Is it possible to have a div move in the opposite direction of mouse scroll, from the top right corner to the bottom left corner?

Currently, it is moving from the bottom left to the top right.

#block {
position: absolute;
top: 400px;
left: 100px;



<script>
$(function(){
    var lastScrollYPos = 0;
    $(window).on('scroll', function(){
        var $this = $(this),
            $block = $('#block'),
            // retrieves the top and left coordinates
            position = $block.offset(),
            // X and Y factors allows to change the diagonal movement direction and
            // degree. Negative values inverts the direction.
            factorX = 1,
            factorY = 1,
            // retrieves current vertical scrolling position and calculate the
            // relative offset
            scrollYPos = $this.scrollTop(),
            offset = Math.abs(scrollYPos - lastScrollYPos),
            // mouse wheel delta is inverted respect to the direction, so we need to
            // normalize it against the direction
            direction = scrollYPos > lastScrollYPos ? -1 : 1,
            // calculates the new position. NOTE: if integers only are used for factors,
            // then `Math.floor()` isn't required.
            newTop = position.top + Math.floor(direction * offset * factorY),
            newLeft = position.left - Math.floor(direction * offset * factorX);

        // moves the block
        $block.offset({ top: newTop, left: newLeft });
        lastScrollYPos = scrollYPos;
    });
});
  </script>

Answer №1

I have reversed the process by changing the direction (as noted) and then including the last Y position instead of deducting it (as indicated)

$(function() {
  var lastScrollYPos = 0;
  $(window).on('scroll', function() {
    var $this = $(this),
      $block = $('#block'),
      // gets the top and left coordinates
      position = $block.offset(),
      // X and Y factors allow for altering the diagonal movement direction and degree.
      // Negative values reverse the direction.
      factorX = -1,
      factorY = -1,
      // fetches current vertical scrolling position and calculates the relative offset
      scrollYPos = $this.scrollTop(),
      // ---- Change the calculation method for the offset
      offset = Math.abs(scrollYPos + lastScrollYPos),
      // mouse wheel delta is opposite to the direction, so normalization against the direction is needed
      direction = scrollYPos > lastScrollYPos ? -1 : 1,
      // computes the new position. NOTE: if only integers are used for factors,
      // `Math.floor()` isn't necessary.
      newTop = position.top + Math.floor(direction * offset * factorY),
      newLeft = position.left - Math.floor(direction * offset * factorX);

    // moves the block
    $block.offset({
      top: newTop,
      left: newLeft
    });
    lastScrollYPos = scrollYPos;
  });
});
.body {
  height: 1500px;
  width: 1000px;
}

#block {
  height: 750px;
  width: 500px;
  background: blue;
  position: absolute;
  top: -700px;
  left: 400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="body">
  <div id="block"></div>
</div>

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

Continuously update the content within a paragraph using jQuery

After searching for a jQuery animation that would constantly change text within a paragraph, I stumbled upon a solution at this link : Text changing with animation jquery. However, I encountered a challenge as I wanted to include a bootstrap button beneath ...

Maintaining a reliable and efficient way to update the userlist in a chatroom using PHP, AJAX, and SQL

I've successfully created a chatroom using PHP, JavaScript, AJAX, and SQL without the use of JQuery or any other tools. I maintain user persistence through session variables to keep users visible on the front page of my website (www.chatbae.com). How ...

Ways to extend div to fill the rest of the page's vertical space

Apologies, my search has yielded many results, but none that directly address my specific issue. It appears that there is a proliferation of div-height problems on this platform. :-( Here is the layout I am working with for testing purposes: <!DOCTYPE ...

Tips on viewing a PDF document directly in the browser instead of saving it to your device

I have a unique api that returns a json-object containing a link to a pdf { pdf_link: 'http://uniqueurl.com/logs.pdf' } My goal is to open this pdf in a separate browser tab when the user clicks on the file name. I attempted to use the url as a ...

Adding data to a defaultContent JSON column in JQuery DataTable using JavaScript

I am working with a dynamic jQuery data table. The final column in my table allows users to delete rows, but I am having trouble passing the itemId value to the specified function within the button's onClick attribute. Here is the code I have tried s ...

Utilize the DataTables plugin to arrange a column based on icons with hidden boolean values in rows

I am currently utilizing the DataTables plugin to enhance my HTML table. While I have managed to successfully implement most functionalities, I am facing a challenge with the boolean column. This particular column consists of icons representing X (value 0) ...

I am looking to optimize my WordPress posts to load in increments as the user scrolls down the page, similar to how Facebook does

I am looking to implement a feature on my WordPress post where the content loads a few at a time as the user scrolls, similar to Facebook. Specifically, I would like my webpage to automatically load 10 posts and then continue loading 10 more as the user re ...

Tips for Loading a Selected Option from an Ajax Call in Angular JS on Page Load

How do I automatically set the selected option from an ajax call when the page loads? I am fetching zones using an ajax call and I want to trigger the change function of the zones on page load in order to set the selected option of the cities select box. ...

Search for text in multiple tables using jQuery and automatically trigger a button click event when the text is found

I am attempting to query certain tables and click a button within a cell of a specific table. Below is the code I am currently using: links[1].click(); iimPlayCode('WAIT SECONDS = 2') var compTabs = window.content.document.getElementById(' ...

What is the best way to implement a CSS transition for styles that are dynamically created by React?

I have a situation where I am using a button component that is styled based on a theme provided by a context: The code in Button.js looks like: () => { const theme = useContext(themeContext); // { primaryColor: "blue" } return <button className ...

What is the best way to extract a single item from an array in Javascript and assign it to a different variable

I am currently dealing with an array of objects structured like this: contacts: [ { id: 1, name: "John Doe", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="066c696e6846616b676f6a2865696b">[emai ...

Missing information in input field using JQUERY

I've been attempting to extract a value from an input tag, but all I keep getting is an empty string. Upon inspecting the frame source, it appears as follows: <input type="hidden" name="" class="code_item" value="00-00000159" /> In order to re ...

Vue and Jexcel: maximizing efficiency with event handling and dynamic calculations

I am trying to utilize the vue wrapper for jexcel and want to trigger the undo function from the toolbar computed field. However, I am facing difficulties accessing the spreadsheet instance as it throws an error saying 'this.undo is undefined.' ...

What is the best way to enable the noWrap feature for a Typography component that is within an Alert or AlertTitle component?

My goal is to have a Typography component truncate overflowing text with an ellipsis. However, I am facing an issue where this doesn't work when the Typography component is nested inside an Alert component. Below is a snippet of the code in question: ...

Is it possible to analyze an API call and determine the frequency of a specific field?

Code: var textArray = new Array(); var allText = results.data._contained.text; for (var i = 0; i < allText.length; i++) { var text1 = allText[i]; var textHtml = "<div id='text_item'>"; textHtml += "& ...

Error Timeout Encountered by Langchain UnstructuredDirectoryLoader

I am facing an issue while trying to load a complex PDF file with tables and figures, spanning approximately 600 pages. When utilizing the fast option in Langchain-JS with NextJS Unstructured API, it partially works but misses out on some crucial data. On ...

A JavaScript object featuring a predefined value

I have a simple goal that I'm unsure about achieving. My objective is to create an object that will return a specific value if no property is specified. For example: console.log(obj) // Should output "123" console.log(obj.x) // Should output "ABC" ...

Is there a way to retrieve two arrays in an Ajax request?

JAVASCRIPT CODE: $.ajax({ url: 'assignavailtrainers.php', data: {action:'test'}, type: 'post', success: function(data) { } }); PHP CODE: <?php $username = "trainerapp"; ...

Enhance CSS delivery for the items listed below

Reduce the delay caused by rendering JavaScript and CSS above-the-fold. There are 16 CSS resources currently blocking the rendering of your page. This delay could be affecting the loading time of your content. To improve this issue, consider deferring or ...

Displaying an interactive 2D floorplan in a web browser with the use of html5 and javascript

In the process of updating my old Flash viewer, I am looking to display interactive 2D floorplans exported from AutoCAD. Currently, I convert the AutoCAD files into XML files containing the X and Y coordinates of the various elements on the floorplan such ...