"Dynamic background image shifts with the movement of the mouse cursor

Is there a way to achieve an effect like this interactive background:

I am looking to make the background image follow the mouse cursor. Is there a simple method to accomplish this without directly using the script from the example?

I have attempted a solution similar to this:

$('#outer').mousemove(function(e){
    var xcoord = e.pageX - this.offsetLeft;
    var ycoord = e.pageY - this.offsetTop;
  if (xcoord <= 1200) {
      $('#bg').css({'right': xcoord});           
  }

   if (ycoord >= 500) {
      $('#bg').css({'left': ycoord});           
  }

Answer №1

The code provided demonstrates how to use CSS Transforms Matrix for changing the position of a background layer. It is important to ensure that the image remains centered during this transformation, as adjusting the right and left positions alone will not achieve the desired effect.

To implement this effect, you can create a layer with absolute positioning that covers the entire screen with some margin, while maintaining a low z-index as a background element. By utilizing the css transform property, you can shift the position of this layer based on mouse movement.

var maxMove = 10;
var d = $(window);
var bg = $("#bg");
bg.width(d.width()+maxMove*2).height(d.height()+maxMove*2).css('top','-' + maxMove + 'px').css('left','-' + maxMove + 'px');

$(document).mousemove(function(event) {
    var xPos = event.pageX;
    var yPos = event.pageY;

    var w = d.width();
    var h = d.height();

    var xShift = ((w/2 - xPos)/w*2)*maxMove;
    var yShift = ((h/2 - yPos)/h*2)*maxMove;

    $("#log").text(xShift);
    bg.css('transform','matrix(1, 0, 0, 1, ' + xShift + ', ' + yShift + ')');

});

Remember to include the necessary CSS styles:

#bg{
    position:absolute;
    background:url(http://lorempixel.com/output/city-q-c-1861-1370-1.jpg) center center no-repeat;
    z-index:-1;
}
body{
    padding:0;
    margin:0;
    overflow:hidden;
}

For more information, refer to this detailed tutorial and live demo.

Learn more about Css Transforms Matrix from this resource here.

Answer №2

After a quick search on the web for your desired outcome, I stumbled upon this helpful link as the very first result: http://jsfiddle.net/geekambassador/a6ekn/

bg.mousemove(function(event) {
  var xPos = event.pageX;
  TweenLite.to(bg, .5, {css:{backgroundPosition:xPos + "px"}});
});

I trust this information will be beneficial to you.

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

Using jQuery to dynamically change the label of a Struts2 checkbox

Currently, I am utilizing jquery to modify the labels of checkboxes. use strict'; $("#chId").click(function () { if (this.checked) { $('#divId').html("Checked"); } else{ $('#divId').html("Un-Checked"); ...

The onPlayerReady function in the YouTube API seems to be experiencing a delay and

After following a tutorial on integrating the YouTube API into my website, I encountered difficulties trying to play a YouTube video in fullscreen mode when a button is pressed. Despite following the provided code closely, I am unable to get it to work as ...

Using CSS to overlay text on an image on a webpage

Can anyone help me with this puzzling scenario? <TD><a href="index-1.html" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('Image20','','images/m21.jpg',1)">Home</a><img src="images/m2.jpg" nam ...

What could be causing the issue of HTML Button not functioning properly with jQuery Webpack?

I'm currently using webpack to build my HTML and javascript files. I have a function defined in index.js and I've attempted the solutions mentioned here, but none of them seem to work for calling the function onclick button. Here is the HTML cod ...

The CSS properties of a div element include the :before pseudo-element with a "shape" style that does

Having trouble finding a way to neatly contain this circle inside the div without any overflow. Looking for an elegant solution! Example of desired outcome .wrapper{ background: #efefef; height: 250px; } .wrapper::before{ width: 300px; height: 300 ...

The power of Rails unleashed through Ajax Remote Javascript

Trying to locate Employees who are engaged in multiple Job roles, I have set up three select boxes that dynamically adjust their options. The problem arises when my CoffeeScript file only triggers once. After the initial selection and rendering of the part ...

What is the best way to utilize jQuery for deleting the final <li> within a <ul> element?

One of my web pages contains an unorganized list similar to this: <ul id="myList"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li>Item 4</li> </ul> How can I target the last ...

How can I use jQuery to automatically generate a random number in a div every 5 seconds?

I am trying to incorporate a dynamic random number feature on my WordPress website, similar to the one seen on "". The number should automatically change every 5 or 10 seconds. ...

Unusual happenings detected in Magellan Fixed with Foundation 5

I need help creating a product summary sidebar similar to Apple's. I'm using Magellan but it seems to break the page when the width is below 960 pixels. It might be related to the table, but I'm not sure. Any suggestions or assistance would ...

In Firefox, the Ajax Call is failing to initiate a response automatically

I am currently working on developing a dynamically generated accordion with nested subaccordions. A filter function has been successfully implemented to manipulate the content on the page using Ajax. In order to achieve this, the following function has bee ...

Why does the jQuery alert trigger only 40% of the time?

JavaScript -> if ($('.pagination').length) { $(window).scroll(function() { var url = $('.pagination .next_page').attr('href'); if ($(window).scrollTop() > $(document).height() - $(window).height() - 1 ...

Elegant Decline of Javascript Functionality - Imported Web Assets

Looking for assistance from experienced JS coders. I'm currently working on a Wordpress website that utilizes jQuery AJAX methods to reload either the entire content area or just the main content section based on different navigation clicks. My aim i ...

Adding information to a database by utilizing Jquery, Ajax, and PHP

Trying to use ajax to submit data to a database has been a challenge for me. Even with a simple code test, I can't seem to make it work. Here is the HTML/ajax code snippet: <?php include("osb.php");?> <script type = "text ...

Turbolinks gem causing ShareThis to malfunction

After adding the turbolinks and jquery-turbolinks gems to my project, I noticed that my ShareThis button no longer pops up when clicked. The ShareThis scripts currently included in my application.html.erb head are: <script type="text/javascript">va ...

What is the best way to eliminate HTML unicode content from the final item in a continuously changing list?

li:after{ content:"\00b6"; } <ol> <li>banana</li> <li>orange</li> <li class="last-class">apple</li> </ol> I am currently working on a dynamic list where the number of <li> tags varies over t ...

Guide to automatically converting Google fonts to base64 for inline use

I am currently in the process of creating my own personal blog using next.js. While everything is going smoothly with the use of Google Fonts for font styling, I have encountered an issue with initial content shift upon loading. This occurs when a new fon ...

Activate the keypress event in jQuery for a text input field

When using the .trigger() method with the Event object, considering the which property, JS char codes from this source, and the code snippet below, why doesn't the #example input receive the character a as an automatically typed value? Have I misinter ...

Extended sticky navigation bar reaching beyond right margin

My website features a navigation bar that is created using the following code: body { margin: 3em; } #navbar { overflow: hidden; background-color: #333; } .sticky { position: fixed; top: 0; width: 100%; } <div id="navbar"> &l ...

React - A guide on accessing the scroll position of a div using JavaScript

Within my side navigation bar, there is a title and other information. The title is fixed in place (sticky) and the sidebar has a height of 100vh. I am looking to add a box-shadow effect to the title div (sticky-title) only when the user scrolls down past ...

Every time I try to set up the MailChimp pop-up javascript, I encounter an Uncaught Error message saying that Bootstrap tooltips need Tether and an Uncaught ReferenceError message

Utilizing Wordpress and Understrap. Upon inserting the following code: <script type="text/javascript" src="//downloads.mailchimp.com/js/signup- forms/popup/embed.js" data-dojo-config="usePlainJson: true, isDebug: false"> </script><script ty ...