Change the x and y positions of several div elements as the mouse moves in JavaScript

I am aiming to create a webpage where multiple divs with text and other content move along the x and y axes of the mouse. The desired effect is similar to parallax scrolling, but I have found that existing parallax plugins are image-based and do not work with div elements. I attempted to write my own JavaScript code, but the divs end up jumping all over the page and cannot be kept in place using CSS. Perhaps someone with more experience in JavaScript can provide insight on how to resolve this issue. Below is the code snippet I have implemented. Looking forward to hearing from you.

HTML:

<div class = "main" id ="scene">

    <div class = "container" id = "home">

      <div class = "kop "> HOME </div>

      <div class = "brood "> 
        <p>
          Etiam rhoncus...
        </p>
      </div>

    </div> <!-- end container home -->


    <div class = "container" id = "visie">

      <div class = "kop"> VISIE </div>
      <div class = "brood"> 
        <p>
          Lorem ipsum dolor sit amet...
        </p>
      </div>

    </div>
</div>

CSS:

.container{
    margin-right: 20%;
    margin-top: 200px;
    margin-bottom: 200px;
    margin-left: 20%;

    font-size: 16px;

    background-color: yellow;

}

.kop{
    font-family: GTWBold;

}

.brood{
    font-family: GTWMedium;

}


#home{
    margin-top: 20px;

}


#visie{
    margin-right: 40%;

}

JS:

$('#scene2').mousemove(function(e){
    var x = -(e.pageX + this.offsetLeft) / 20;
    var y = -(e.pageY + this.offsetTop) / 20;

    var h = document.getElementById('home');
    h.style.position = "absolute";
    h.style.left = x+'px';
    h.style.top = y+'px';   
    h.style.width = "500px";

});

Answer №1

When you use the CSS property <code>position: absolute
, it takes an element out of the regular flow of elements, causing a shift in everything else on the page. Additionally, adjusting the width of an element after it has been rendered can also lead to shifts because it affects how the height at which #visie is displayed.

One solution to this issue is to try the following code snippet:

$('#scene').mousemove(function(e){
  var x = -(e.pageX + this.offsetLeft) / 20;
  var y = -(e.pageY + this.offsetTop) / 20;

  var h = document.getElementById('home');
  h.style.position = "relative";
  h.style.left = x+'px';
  h.style.top = y+'px';
});

You can see an example of this solution in action here: https://jsfiddle.net/pqur9wxa/1/

If you want to observe both elements moving simultaneously, check out this demo: https://jsfiddle.net/pqur9wxa/2/

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

Make sure that the input field and label are aligned side by side in the

Is there a way to arrange the following HTML in the specified layout? <div> <div> <label>Counterparty</label> <input id="paymentsApp-inpt-cpty" ng-model="selectedPaymentCopy.counterparty" ng-required="true" ...

Ways to determine in each() whether the current div contains a specific class or not

My task is to verify if the div contains the class 'completed', and then insert the text "Hello". However, my current code is displaying "Hello" even when the div does not have the class 'completed'. jssfiddle ...

Begin the animation again by hitting the start button, using the burst-engine and canvas

I have successfully created a simple animation using Burst Engine and HTML5. My goal is to make the start button trigger the animation to restart if pressed twice. Currently, when I press it, the animation just starts and nothing else happens. I suspect t ...

Leveraging Discord.js to retrieve all messages sent while the bot was inactive

My plan is to create a bot that will store all messages sent in a channel into a txt file on my computer. However, the challenge is that since my computer is not always on when the bot is running, there are gaps in the stored messages in the .txt file. I a ...

Incorporating the click function into dynamically created divs using jQuery

When I receive an array from AJAX, I am dynamically creating Divs based on the number of items in the array. Each div has a unique Id and I want to attach a Click event to all of them. The goal is for the user to click on one of the generated divs to tri ...

Is there a way to dynamically calculate the total of a column when a new row is added using Javascript?

I am new to both javascript and cakephp. I successfully implemented a feature that allows me to add a new row using javascript, but now I am looking to calculate the total sum of the "amount" column whenever I input a value in the amount field. Below is th ...

MongoDB suggests

I'm currently developing an app that requires autocomplete functionality for search. I've started implementing it using regular expressions (regexp), but I'm unsure if this is the optimal approach. Each new character input in the search bar ...

Accessing a variable from an external JavaScript file using jQuery

Can someone help me out with this issue I'm facing? I am having trouble getting a string returned to a variable in my embedded Javascript code. token.js: function token () { return "mysecretstring"; } HTML Code: <!DOCTYPE html> <h ...

The element will display above all other elements in its parent container

I am currently developing a React application, and the code structure is set up as follows: <Div> <Div style={{maxHeight:'60vh'}}> //This section includes the code for displaying a list item. Each item has its context menu that can ...

Error Alert: JQuery Pop Up Issue

Struggling with getting my JQuery Pop-Up Box to work properly. Any guidance for a newbie like me on how to fix it would be greatly appreciated. Here's the code I've been working on: <!-- POP UP HTML --> <div class="infocontainer"> ...

How can we effectively manage error responses and retry a failed call in NodeJS without getting tangled in callback hell?

I am in search of an effective approach to handle the given situation. I am curious if employing promises would be a helpful solution? Situation Overview: When a call retrieves a callback, and this callback receives an error object as a parameter. My obj ...

Discover which students have conflicting schedules with themselves

To put it simply, my question involves a table display where student numbers (USN) are concatenated in groups and the entire row is displayed using a foreach loop. Row 1: Subject 1 - 22/07/2015 - 08:00 - 1XX10XX086, 1XX10XX087, 1XX09XX088 Row 2: Subject ...

Form a collection of JavaScript arrays using a string that includes strings

Here is a string that needs to be converted into a JavaScript array: ['Value',2],['Value2',4],['Value3',10] To convert this to a JavaScript array, the following code can be used: var tmpStrings = "['Value',2],[&ap ...

What is the functionality behind app.listen() and app.get() in Hapi.js, Restify, and Koa?

Using the http node module, which consists of only native modules, how can I create a custom version of app.listen() and app.get() by utilizing the http module with a constructor? var app = function(opts) { this.token= opts.token } app.prototype ...

What is causing the slow performance of this JavaScript array retrieval?

I am working with a large array called frames_to_boxes, consisting of 5000 elements. Each element is an array of Objects belonging to the Box class: class Box { constructor(x, y, width, height, frame, object_class, id) { this.x = x; this.y = y; ...

The canvas's document.getElementById function is unable to find any matching element,

Hello everyone, I am currently diving into the world of javascript and trying to expand my knowledge. However, I have encountered a problem that has me stumped, and I could really use some assistance. While exploring, I came across this page: http://www.w ...

Modifying Array Values in Angular 7

I am currently dealing with a complex array where questions and their corresponding answers are retrieved from a service. Upon receiving the array, I aim to set the 'IsChecked' attribute of the answers to false. The snippet of code I have written ...

Ways to align text and horizontal rule perfectly within a div container?

I need to add some text to my <div> container and make sure it is centered. .hr { background: green; height: 50px; margin: 65px 0; width: 3000px; } <div class="hr"></div> This is an illustration of my project: A picture showing m ...

Can you please provide the CSS code that would style this table in a similar manner?

I am interested in utilizing the design of this table, but how can I update it to meet CSS standards and HTML5 equivalents? <html> <head></head> <body> <table border="1" bordercolor="#000000" style="background-color:#ffffff" w ...

Displaying content in a hidden div on click event

I am part of a volunteer group for prostate cancer awareness and support, and our website features multiple YouTube videos that are embedded. However, the page has been experiencing slow loading times due to the number of videos, despite them being hidden ...