What is the method to track the movement of the mouse in the reverse direction?

I am looking to create a unique div that moves in the opposite direction of the mouse cursor within another div called .box. As the mouse moves, I want the red box to create a subtle parallax effect by slightly moving in the opposite direction. Instead of moving at the same speed as the mouse, I want the box to move just a little bit to achieve the desired effect. Additionally, I would like the box to be centered around the mouse cursor.

I have already implemented a script that allows the red box to follow the mouse cursor, but I am unsure of how to achieve the desired effect described above.

$(document).ready(function(){
  $('div.container').on('mousemove',function(e){
        var x = e.pageX - this.offsetLeft;
        var y = e.pageY - this.offsetTop;
        $('div.box').css({'left': x, 'top': y});
  });
});

http://codepen.io/anon/pen/zBrkGa

Answer №1

It might be worth trying to replace top with bottom and left with right to see if that resolves your issue, like so:

$('div.box').css({'right': x, 'bottom': y});

$(document).ready(function() {
  $('div.container').on('mousemove', function(e) {
    var x = e.pageX - this.offsetLeft;
    var y = e.pageY - this.offsetTop;
    $('div.box').css({
      'right': x,
      'bottom': y
    });
  });
});
.container {
  margin: 0 auto;
  width: 300px;
  height: 300px;
  border: 1px #000 solid;
  position: relative;
}
.box {
  width: 50px;
  height: 50px;
  border: 1px #000 solid;
  position: absolute;
  right: 200px;
  background: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="container">
  <div class="box"></div>
</div>

Updated: Make sure that the box stays within a range of 100px with a slight delay

$(document).ready(function() {
  $('div.container').on('mousemove', function(e) {
    var x = (e.pageX - this.offsetLeft);
    var y = (e.pageY - this.offsetTop);
    if(x<100||x>200||y>200||y<100) return false;
    setTimeout(function() {
      $('div.box').css({
        'right': x,
        'bottom': y
      }).text(x+','+y);
    }, 500);
  });
});
.container {
  margin: 0 auto;
  width: 300px;
  height: 300px;
  border: 1px #000 solid;
  position: relative;
}
.box {
  width: 50px;
  height: 50px;
  border: 1px #000 solid;
  position: absolute;
  right: 200px;
  background: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="container">
  <div class="box"></div>
</div>

Answer №2

$(document).ready(function(){
 $('div.container').mousemove(function(e){
  let mouseX = e.pageX;
  let mouseY = e.pageY;

   $(this).children('.box').css({
    'transform': 'translate(' + mouseX / -80 + 'px ,' + mouseY / -80 + 'px)
   })
  });
});

This code snippet uses negative numbers to make the object or div (.box) move in the opposite direction of your mouse

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

Optimal methods for creating large files using jQuery or Java

I am currently working on a web application using jQuery and Java, and one of my tasks involves generating a report from database records. This report should be downloadable in csv, xls, and txt formats. The number of records in the file can vary, sometime ...

Eliminate spaces within a string using JavaScript

In my quest for knowledge about trimming strings in JavaScript, I came across this intriguing discussion with a regex-based solution. After learning from the thread, I was under the assumption that trim would eliminate the space between "Hello" and "World ...

Vue select component not refreshing the selected option when the v-model value is updated

Trying to incorporate a select element into a Vue custom component using the v-model pattern outlined in the documentation. The issue at hand is encountering an error message for the custom select component: [Vue warn]: Avoid directly mutating a prop as i ...

Troubleshooting automatic login problem in VB 2013 settings

For my application, I am utilizing the most recent version of Awesomium's WebControl. The goal is for it to automatically log in when it reaches "accounts.google.com/ServiceLogin" by executing some Javascript. In my.settings.java file, I have the foll ...

What is the best way to handle responses in axios when dealing with APIs that stream data using Server-Sent Events (S

Environment: web browser, javascript. I am looking to utilize the post method to interact with a Server-Send Events (SSE) API such as: curl https://api.openai.com/v1/completions \ -H "Content-Type: application/json" \ -H ...

Upon transitioning from typescript to javascript

I attempted to clarify my confusion about TypeScript, but I'm still struggling to explain it well. From my understanding, TypeScript is a strict syntactical superset of JavaScript that enhances our code by allowing us to use different types to define ...

Why does pressing "enter" create a line break in HTML when typing?

Apologies in advance for what may seem like a simple CSS issue that I couldn't find an answer to on Stackoverflow. Here's the JSfiddle link: https://jsfiddle.net/kwende/fqxna79a/ In the code, you'll see two div tags: <div id="left">L ...

Developing a Chrome browser extension tailored for parsing unique file formats

Currently, I am working on developing a compiler for a unique conditional formatting language. My aim is to enable the capability of opening files in my language directly in Chrome by simply double-clicking on them in File Explorer (I am currently using Wi ...

Combine object attributes to create a new column in a table

Check out this plunker I created. What is the most efficient way to merge the contents of $scope.blacklist into $scope.friends when ng-click="showColumn('Blacklist');" is triggered, and also add a new column named Coming to the table. Ng-App &am ...

Is there a way to make my DIVS update their content dynamically like buttons do, without manually adding an onclick function in the HTML code?

I am currently customizing a WordPress theme that lacks the option for onclick events on div elements. However, I can assign classes and IDs to them. In my design, I have four spans in a row, and when each span is clicked, I intend for the corresponding p ...

What is the best way to generate a new div element when the content exceeds the preset height of the current div?

CSS .page{ width: 275px; hight: 380px; overflow: auto; } HTML <div class="page">dynamic text</div> Is there a way to automatically create new div elements when dynamic text overflows past the fixed height of the init ...

In what way can I utilize the request object within a promise that is nested?

I am currently working on a Nuxt server side rendered application using the express framework for authentication with the openid-client package. My goal is to store the retrieved token in the express session, but I am facing an issue where the request mode ...

What is the most effective way to add HTML from a dynamically loaded document using AJAX?

I am attempting to attach the information from a .html file to the body of my main webpage. Essentially, I am striving to create a reusable section of html that can be loaded into any page with a basic JavaScript function. Below is the content of my navig ...

What is the best way to initiate a change event using JavaScript?

I am attempting to enable my 4th checkbox automatically when there is a new value in the textbox (myinput). If the textbox is empty, I want to disable it. Currently, you have to tab out before the change event is triggered. Also, how can I check for an e ...

Removing information from the app.component.html file in Angular 6 and reflecting those updates in the view

I currently have a service that retrieves a list of data and displays it within the app.component.html. Below is the code snippet used to display the data: <ul> <li *ngFor="let data of retrieveData"> {{ data.id }} - {{data.title} ...

Validating Form Inputs using JQuery and Bootstrap 4 to Enhance User Experience

I came across a helpful post about using Bootstrap with jQuery Validation Plugin, but it's specifically for Bootstrap 3, not Bootstrap 4. I've been trying to integrate JQuery Validate with Bootstrap 4, but I'm struggling to make the label a ...

How to resolve preventDefault issue on else condition during form submission in CoffeeScript on Rails 4

After submitting a form, I have implemented a code to prevent the page from refreshing and perform different actions based on certain conditions. Everything works as expected except for one scenario where the page still refreshes after executing the ELSE c ...

Is it necessary to clean and reinstall node_modules every time I deploy in a production environment?

We manage over 10 production servers and each time we update our dependencies, performing a clean installation seems more controlled but also slower. The issue is that the devops team is concerned about the time it takes to perform a clean npm install aft ...

Manipulate a value using JavaScript

While the intention is for the button value to switch between 1 and 0, the echo $_POST["ordina"] consistently returns 1. Despite checking the code multiple times, I am unable to identify the issue. <script> function order() { if (document.ordination ...

Attempting to place my icon font in a higher position than my link to achieve a similar effect to the one I am currently experiencing with my

I am currently working on a menu design that incorporates icons (images) above my menu links. However, I have decided to switch from using icon images to utilizing icon-fonts from the 'Font-Awesome' library. Despite this change, I am struggling ...