Try using CSS3 translate instead of relying on offset positions for top and left

Can CSS3 translate transforms be used with jQuery offset instead of top/left position? The current setup seems a bit buggy and slow. Any suggestions or insights on improving this code?

$('.artists-list-container ul li a').on('mouseenter', function() {
    var image = $(this).parent('li').find('.image-container');
    $(this).parent('li').addClass('active');
    image.show();
    $(document).mousemove(function(e) {
        image.offset({
            left: e.pageX,
            top: e.pageY
        });
    });
});

I tried this alternative approach but it doesn't track the mouse movement accurately.

$(document).mousemove(function(e) {
    image.css({transform: 'translateX(' + e.pageX + 'px) translateY(' + e.pageY + 'px)'})
});

Answer №1

The current code in question translates the element by an absolute number of pixels, which may result in a space between the mouse pointer and the actual position of the image if the element is already positioned at an offset from (0,0) of the document due to extra elements or margins/paddings.

To address this issue, it's important to first determine the original position of the element and then calculate the translation values relative to that position. Below is a snippet demonstrating this:

  • $(document).ready(function() {
      var image = $('li').find('.image-container');
      var position = image.offset();
      $(document).mousemove(function(e) {
        image.css({
          transform: 'translateX(' + (e.pageX - position.left) + 'px) translateY(' + (e.pageY - position.top) + 'px)'
        })
      });
    })
    ul {
      list-style-type: none;
    }
    img {
      vertical-align: top;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <ul>
      <li>
        <img class='image-container' src='http://lorempixel.com/200/200/nature/1' />
      </li>
    </ul>

The use of vertical-align:top; on the img tag is crucial in the above code snippet because by default it is set to baseline. This setting affects the positioning in relation to the baseline rather than the actual top of the image itself.

In terms of browser compatibility, the problem mentioned earlier seems to be specific to Chrome only.


A working demo showcasing the proper functionality even when there are additional elements in the DOM preceding the image can be seen below:

  • $(window).load(function() {
      var image = $('li').find('.image-container');
      var position = image.offset();
      $(document).mousemove(function(e) {
        image.css({
          transform: 'translateX(' + (e.pageX - position.left) + 'px) translateY(' + (e.pageY - position.top) + 'px)'
        })
      });
    })
    ul {
      list-style-type: none;
    }
    img {
      vertical-align: top;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div>Some content before the image</div>
    <p>Some other content before the image</p>
    <ul>
      <li>
        <img class='image-container' src='http://lorempixel.com/200/200/nature/1' />
      </li>
    </ul>

It's worth noting that when dealing with multiple images prior to the current element, calculating offsets after those images are fully loaded ensures accurate positioning based on the actual image height rather than just the line height of the element.

The corrected version considering image loading timing is displayed below:

  • $(window).load(function() {
      var image = $('li').find('.image-container');
      var position = image.position();
      $(document).mousemove(function(e) {
        image.css({
          transform: 'translateX(' + (e.pageX - position.left) + 'px) translateY(' + (e.pageY - position.top) + 'px)'
        })
      });
    })
    ul {
      list-style-type: none;
    }
    img {
      vertical-align: top;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div>Some content before the image</div>
    <p>Some other content before the image</p>
    <img src='http://lorempixel.com/100/100/nature/1' />
    <ul>
      <li>
        <img class='image-container' src='http://lorempixel.com/200/200/nature/1' />
      </li>
    </ul>

All code snippets have been tested for compatibility across various browsers including Chrome, Opera, Firefox, IE, and Edge.

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

Exploring the power of DOM manipulation in both jQuery UI and AngularJS UI Router

I have a query regarding the integration of jQuery UI and AngularJS UI Router. My aim is to incorporate jQuery UI themes into my application, however, when using AngularJS UI Router, I face issues with an incomplete DOM tree. Is there a way to successfull ...

The art of encapsulating JSON response objects in Ember Objects with a deep layer of wrapping

Currently, I am engaged in a project using Ember where I retrieve a complex JSON response in a Route's model function. In the associated template, I exhibit attributes of the response. Some of these attributes allow for specific actions that result in ...

Having trouble getting Visual Studio Code to execute my build command in launch.json

Whenever I run this specific command in a command prompt, everything works perfectly: browserify -u jquery /public/index.js -t babelify -o /public/scripts/bundle.js & node /server.js But when attempting to integrate it into the program section of my ...

What is the best way to conceal a button before printing and have it reappear once the printing process is finished?

I have a button on my webpage with the id "print_req" that is used to trigger a JavaScript function for printing the page. I want this button to be hidden during the printing process and then reappear afterwards, so it does not show up in the printed docum ...

Error encountered: Difficulty rendering Vue 3 components within Google Apps Script

Currently delving into Vue and Vue 3 while coding an application on Google Apps Script. Following tutorials from Vue Mastery and stumbled upon a remarkable example by @brucemcpherson of a Vue 2 app functioning on GAS, which proved to be too challenging in ...

Revamp the md-select Container

Hello there! I'm looking for a stylish way to revamp the design of the md-select Window. Specifically, I aim to customize the background and hover effects. Despite my attempts to modify the .md-select-menu-container in CSS, it proved unsuccessful. I ...

Flexbox implemented for responsive Three Column Layout

Recently, I set up a small poll with three layout columns. On Desktop, everything looks great but the problem arises when viewing it on a mobile screen. People are displayed one under the other followed by the questions. I want to rearrange it so that each ...

Guide to automatically refreshing a page every 30 seconds for a total of 5 times

Is there a way to automatically refresh a page 5 times with a delay of 30 seconds between each refresh without causing the entire page to reload? I'm trying to avoid using the document.location.reload() JavaScript function as it reloads the entire pag ...

What could be the reason that my for loop executes only when it is embedded within a while loop?

Hey there, I've been trying to understand why this code snippet works when the while loop is included: some = 0 n = 5 while some == 0: for title in itertools.islice(driver.find_elements_by_css_selector("a[class='link-title']"), ...

The text feature for the Google Places API is not displaying properly within the MUI TextField

For address auto-generation, I am currently utilizing the Google Places API. I have a regular input tag in my HTML where users can type their input and see Google Places suggestions in the dropdown - all working perfectly. However, when I switch to using m ...

The jQuery function text().replace('','') is failing to work properly

After spending countless hours attempting to remove a text string that I previously appended, I am still struggling. The script I have is responsible for managing an accordion and unfortunately contains some redundant text. My goal is to add and remove th ...

Spot the columns generated by CSS and incorporate a new column using JavaScript

Exploring a column newspaper-like layout has led me to wonder if there is a way to use CSS or JavaScript to identify columns (or column breaks) and dynamically insert content between them with JavaScript. The concept involves having a layout with 100% hei ...

Accordion jQuery failing to display tabs

I have a question about using 2 jQuery accordions with tabs inside them. Everything seems to be working, but when I try to expand the second accordion, the two tabs inside don't render properly. I'm not sure what the issue is. Any help on this wo ...

I am experiencing an issue with my route where the Passport JWT req.user is unexpectedly undefined

Setting up JWT with my express app has been quite the challenge! Despite getting most of it working, I've encountered a strange issue. My register and login routes are generating valid tokens and authentication works fine in the '/users' rou ...

Enhance the appearance of a custom checkbox component in Angular

I developed a customized toggle switch for my application and integrated it into various sections. Recently, I decided to rework it as a component. However, I am encountering an issue where the toggle switch button does not update in the view (it remains t ...

Set the desired font size to 2 using CSS styling

I need to work with a different company's markup code, and it's quite unconventional. I'm only able to edit the CSS, not the HTML itself. The markup code I have to deal with looks like this: <p> <font size="2">Headline</fon ...

Having difficulty parsing the JSON data in order to create a visual graph

I am a beginner with jQuery and json, attempting to create a graph following the example from http://www.highcharts.com/stock/demo/ This specific graph utilizes data retrieved from a json file http://www.highcharts.com/samples/data/jsonp.php?filename=a ...

The alignment of flex items is not consistent in Webkit browsers

One of the issues I am facing involves a text field that contains a cogwheel symbol which opens a popup menu with different search options. The layout is set up using a flexible box model for certain elements. After testing in Firefox, the display is as e ...

Create a folder in jsTree - the folder is generated before the user enters a name for it

I own a tree that I am able to create folders on. However, there is an issue with the process that is also present in the filebrowser demo found in the jsTree download. It's a user experience problem, so I will try my best to explain it clearly: 1) ...

How to split a string in JavaScript using white space

I'm looking to separate a string while preserving white space, for example: var str = "my car is red"; var stringArray []; stringArray [0] = "my"; stringArray [1] = " "; stringArray [2] = "car"; stringArray [3] = " "; stringArray [4] = "is"; string ...