The changing perspective in relation to the current position of a background

I am currently working on implementing a parallax effect, which is mostly successful. However, I have encountered a minor issue. Instead of the parallax effect being relative to the element's current position, it abruptly jumps to position 0. How can I adjust the code to make the parallax effect relative to its current position?

Below is the JavaScript code I am using:

$("#caveConfron").mousemove(function(e){
    var x = e.pageX - this.offsetLeft;

    var alreadyY = $("#caveConfron").css("backgroundPositionY");

    $("#caveConfron").css({"backgroundPosition":-(x/85)+"% 0%"});
});

Here is the CSS code related to the element:

#caveConfron{
    width:242px;
    height:344px;
    border:5px solid black;
    background:url('../img/caveConfrontBg.jpg') no-repeat center top;
    position:relative;
}

You can see an example of the issue here: http://jsfiddle.net/gNCjS/

Answer №1

After extensive trial and error, I managed to identify the issue at hand.

Primarily, I realized that when the mouse intersects the center of the div, the x-coordinate of the mouse position should be "0". Therefore, I made the following adjustments without altering the CSS:

$("#caveConfron").mousemove(function(e){
    var x = e.pageX - this.offsetLeft;

    var reduce = $(this).width()/2;

    $("#caveConfron").css({"backgroundPosition":(((-x+reduce)/55)+50)+"% 0%"});
});

The variable reduce is set to half of the div's width. Subsequently, I negate the value of x while adding it to the value of reduce to ensure that if the mouse position of x goes beyond halfway through the div, it will become positive, thus maintaining the center as "0." Additionally, I divide by 55 to minimize abrupt movements on the x-axis, providing a smoother transition (you can adjust this value for a more significant jump if desired; it worked well for my purposes). Furthermore, I add 50 because in the original CSS, the background's position is centered, coinciding with a value of 50%.

I trust my explanation was clear and helpful!

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

The Node.js Express Server runs perfectly on my own machine, but encounters issues when deployed to another server

I've encountered a strange issue. My node.js server runs perfectly fine on my local machine, but when I SSH into a digital ocean server and try to run it there, I get this error. I used flightplan to transfer the files to the new machine. deploy@myse ...

Reducing size and Assembling JavaScript and CSS

I find myself in a bit of a dilemma when it comes to using just one JS file and one CSS file for a website. Let me elaborate: As someone who mainly works with CMS platforms like Joomla, I often run into issues during page speed tests where experts recomme ...

Output PHP Array as JSON for specific content based on conditions

My code features "conditional content" based on the type of the content, as shown below: //--- SQL query to retrieve content --- if(mysqli_num_rows($niceSQL) > 0) { while($something = mysqli_fetch_array($niceSQL)) { $type = $something["typ ...

Unable to retrieve the field value from the Json Object

I have a JSON object that I need to parse and display in a data table, but I'm having trouble reading the contents of the object. Here is my JavaScript function: finalGrid: function(data){ console.log("Final Grid"); var strJson = JSON.strin ...

Lamenting the Perils of Losing AngularJS Rootscope Data upon Refresh

Currently, I am facing an issue in AngularJS 1.x. When I save a value in the $rootScope and pass to the next page or router, unfortunately, the $rootScope value gets lost upon refreshing the page (F5/Window Reload). I need a solution that doesn't inv ...

Choosing a tab on a website using Python and Selenium

Displayed above is an image of tab codes found on a web page: https://i.sstatic.net/M54VH.png The tabs are named Overview, Information, and Audit (Please refer to the top part of the image). While I am able to open the tab by clicking with a mouse, I am f ...

What is the best way to send props to a component that is exported using a Store Provider?

I'm trying to export my react component along with the redux store Provider. In order to achieve this, I've wrapped the component with an exportWithState callback. However, I'm facing an issue where I can't seem to access the props that ...

Optimal method for streaming and viewing an mkv video captured with ffmpeg in a web browser

Is there a way to stream a video recorded with ffmpeg in a web browser using the HTML5 video tag? I currently have this code on my page, with the URL pointing to a video file (example.mkv) being recorded by ffmpeg. <video class="video-player" controls ...

Dynamic Cell Class Assignment in Ag Grid

My Div's dimensions can change based on user interaction, with the div containing an ag-grid component. Initially, the div/grid loads in a compressed size, so I've applied specific classes (like small font-size, height, padding, etc.) to eliminat ...

How can I pass function arguments dynamically to a nested function in Node.js?

Currently using Node 6.11.0, I am attempting to accomplish the following dynamically: const parentFunc = (arg1, arg2, arg3, arg4) => { childFunc('foo', arg1, arg2, arg3, arg4); }; I have attempted this method (without success): const pare ...

Is there a way to showcase a jquery calendar with highlighted days that are unable to be clicked on (read only)?

I'm using the Jquery calendar to showcase daily room capacities, which is functioning well. However, I now want to display this calendar on my home screen in read-only mode. The days should not be highlighted, as there is no interactive feature and us ...

"Using the d-flex class with Bootstrap 4 tables does not allow them to expand to

Since the latest version of Bootstrap 4, it has become more challenging to apply classes like col-md-2 directly to the tr or td elements of a table. A possible solution is to use class="d-flex" in the parent element: <tr class="d-flex"> However, w ...

What causes the appearance of 'GET/ 304 --' in my code? (vue.js, express)

While attempting to fetch data on the client-side using axios in vue.js, I encountered a server-side error with the code 'GET/ 304 --' The reason for this occurrence is unclear to me and I am unsure of how to troubleshoot or resolve it. If I re ...

Ensuring proper alignment of images and text in HTML when resizing

Trying to show an image and text side by side, I'm using the following code: div.out { background-color: silver; border: 1px solid black; padding: 10px; display: flex; } div.right { order: 1; background-color: white; border: 1px soli ...

What steps do I need to take in order to show the present value using a range input?

Hey there! I'm working on a code in HTML that includes an input of type range. Here's what it looks like: This is my input: <input type="range" min="1" max="100" value="50" class="slider" id="myRange"> Unfortunately, I'm unable to s ...

Preserving the initial input values in a secure manner for future reference, utilizing either an object or a

Recently, I've started revisiting a script I created a while back that checks for changes in a form to prompt a message asking 'Would you like to save your changes?'... One thing that's been on my mind is whether I should store the ori ...

If either the form is invalid or has been submitted, disable the button

Is there a way to either disable the button when the form is invalid or after the user clicks it, but not both at the same time? How can I incorporate two statements inside the quotes for this purpose? I attempted the following code, but it didn't w ...

Toggle the class and execute the order within a jQuery script

When the mouse moves in, the jQuery trigger enters the status. $(".test").bind("mouseenter mouseout", function(event) { $(this).toggleClass("entered"); alert("mouse position (" + event.pageX + "," + event.pageY + ")"); }); .entered { ...

Node functions continue to run smoothly without affecting the loop

I am working on a webdriverjs application and I am trying to determine when jQuery has finished its processes on the page. I have implemented some methods, but it seems that even when the condition is supposed to trigger an else statement and stop the loop ...

Having trouble loading an image after successfully connecting to an API with react.js

I've been working on a custom fetch component to load images from the "the dog API" onto my page. However, I'm facing some issues with getting the images to display correctly. Can anyone spot what might be missing in my setup? App.js import &apo ...