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

Ways to stop a background image from repeating?

<div style="background-image: url('https://i.ibb.co/v1B855w/bg15.png'); color: #000000; background-color: #000000; background-attachment: fixed; text-align: center;"><img src="https://i.ibb.co/L6zQY0S/name6.png" /> ...

Having difficulties executing AJAX requests on Codepen.io

My CodePen project that I created 6 months ago is no longer functioning properly. The project includes an Ajax call to retrieve data using jQuery.ajax(). When attempting to load the content from CodePen via https, even though the ajax request is through h ...

Display the AJAX loading indicator with a slight delay rather than instantly

For my latest web app project, I have incorporated numerous ajax calls. While the majority of these calls are quick and provide immediate responses, I am interested in implementing an ajax loader to display when calls take longer than 250ms. This will pr ...

Navigating through pages using Jquery's show and hide functionality

How come my item is not returning? I used the .show() method on the item. <div id="back">< back</div> <div class="item">item</div> <div class="content">My content</div> $(function(){ $('.item').on(&apo ...

JS: Decreasing the counter while calling the hide() function

If I have a standard count <?php echo "Today (".mysql_num_rows($query)."); ?> It will display as Today (10) if there are 10 entries. Beneath this counter is a while() loop that displays all the rows in a <tr>. Within each <td> in the ...

My fixed navigation bar is being impacted by the link decorations

I'm fairly new to web development, so please be patient with me. I am trying to achieve a design where my image links are displayed at half opacity by default and then switch to full opacity when hovered over. While this is working as intended, it see ...

Using Next Js for Google authentication with Strapi CMS

Recently, I've been working on implementing Google authentication in my Next.js and Strapi application. However, every time I attempt to do so, I encounter the following error: Error: This action with HTTP GET is not supported by NextAuth.js. The i ...

Error occurred while looking for user by ID in the everyauth

I previously had a working example with express 2.*, but now I am transitioning to version 3.*. The issue arises during authentication with Facebook, causing some problems. Everything works fine until everyauth makes the GET request to Facebook and then re ...

How do I get my navbar to change color using a JavaScript scroll function?

I've been struggling with changing the color of my navbar when it's scrolled. I have some JavaScript code at the bottom that should handle this, but for some reason, it's not working as expected. I've double-checked that my bootstrap CD ...

Mobile video created with Adobe Animate

Currently, I am designing an HTML5 banner in Adobe Animate that includes a video element. However, due to restrictions on iPhone and iPad devices, the video cannot autoplay. As a workaround, I would like to display a static image instead. Can anyone provid ...

Conceal specific image(s) on mobile devices

Currently, I am facing an issue on my website where I need to hide the last two out of six user photos when viewed on mobile or smaller screens. I believe using an @media code is the solution, but I'm unsure about the specific code needed to achieve t ...

The dual-file upload feature of the jQuery ajaxForm plugin

After extensive searching online, I have yet to find an answer to my problem. The issue at hand is that when using the ajaxForm malsup plugin, it submits my files twice. HTML: <form id="gallery" enctype="multipart/form-data" action="/upload-gallery.p ...

The Facebook Customer Chat Plugin embedded within an iframe

Can the Customer Chat Plugin be used within an iframe? When adding content-security-policy: frame-ancestors IFRAME_DOMAIN, it displays the message Refused to frame 'https://www.facebook.com/' because an ancestor violates the following Content Se ...

Using Backbone for the front end and Node.js for the backend, this website combines powerful technologies

Currently, I am in the process of developing a new website that will function as a single-page application featuring dialog/modal windows. My intention is to utilize Backbone for the frontend and establish communication with the backend through ajax/webs ...

Implement a jQuery DataTable using JSON data retrieved from a Python script

I am attempting to create an HTML table from JSON data that I have generated after retrieving information from a server. The data appears to be correctly formatted, but I am encountering an error with DataTable that says 'CIK' is an unknown para ...

Image transformed by hovering effect

I've been attempting to add a hover effect to the images in my WordPress theme. The images are displayed in a grid format, created by the featured image on the posts. The grid layout is controlled within content.php <?php /** * controls main gri ...

Avoid clicking in areas outside the perimeter of the blue circle in the SVG

Is there a way to restrict clicking outside the blue circle? The goal is to only allow opening by clicking on the svg itself, This includes everything, even white space inside the svg. How can this be achieved in the code? The current behavior is that ...

Steps to create a "reset fields" option for specific input fields

Is there a way to create a link that clears the input fields in a specific column? I have managed to style a button to look like a link: <input type="reset" value="clear fields" style=" background:transparent; border: none; color:blue; cursor:pointer"& ...

How to Stop Element Flickering While Hovering in Selenium IE Webdriver

My code is functioning perfectly in Firefox, but when I try it on Internet Explorer, there is flickering. Here is my code: WebElement mouseOver= driver.findElement(By.linkText("abc")); //I'm locating the element by link text. Selenium finds the ...

Wrap all temporary array elements of the same type within an object

Extracted from a json api, the following snippet of content showcases various titles and content types: contents: [ { title: "some title", content_type: 2 }, { title: "some title", content_type: 2 }, { title: "some title", content_type: 1 }, { title: ...