jQuery divs seem to "gaze up" towards the mouse pointer

I am attempting to recreate a fascinating effect using jQuery - where "cards" move in response to the mouse cursor as if they are looking up at it.

I have come across a script that almost achieves what I need, but I require the ability to control the movement of the cards on the x and y axes individually. Additionally, it would be ideal if each card could have its own center point rather than being centered on the screen. This way, when the cursor hovers over a specific card, only that card will align flat while others look towards the mouse.

Here is the HTML structure:

<div id="collections">
        <article>
        </article>
        <article>
        </article>
        <article>
        </article>
        <article>
        </article>
        <article>
        </article>
    </div>

Corresponding CSS styling:

div#collections {
    width: 100%;
    height: 100%;
    position: relative;
    z-index: 6;
}
    div#collections article {
        width: 20%;
        height: 15%;
        background: red;
        position: absolute;
        transform-style: preserve-3d;
        transform-origin: center center; 
        backface-visibility: visible;
        transform: rotateX( 0deg );
        transition: transform 50ms ease;
    }
        div#collections article:nth-child(1) {
            left: 20%;
            top: 30%;
            background: blue;
        }
        div#collections article:nth-child(2) {
            left: 40%;
            top: 10%;
            background: black;
        }
        div#collections article:nth-child(3) {
            right: 10%;
            top: 20%;
            background: pink;
        }
        div#collections article:nth-child(4) {
            left: 10%;
            bottom: 20%;
            background: purple;
        }
        div#collections article:nth-child(5) {
            right: 30%;
            bottom: 30%;
            background: green;
        }

    .notransition,
    .notransition div#collections,
    .notransition div#collections article {
        transition-duration: 0 !important;
        transition-delay: 0 !important;
    }

    .transition-reset,
    .transition-reset div#collections,
    .transition-reset div#collections article {
        transition-duration: 600ms !important; 
    }

The jQuery function for this effect:

$.fn.mcollections = function() {
    var doc = $(document),
      body = $("section#home"),
      docWidth = doc.width(),
      docHeight = doc.height(),
      horiz = 0,
      vert = 0,
      x,
      y,
      range = 30
      objekt = this;

    console.log("docWidth: "+docWidth);
    console.log("docHeight: "+docHeight);
    console.log("range: "+range);

    function noTransition() {
      body.removeClass("transition-reset"); //addClass("notransition");
    }

    function followMouse() {
      horiz = ((range*2)*(x / docWidth))-range;
      vert = -(((range*2)*(y / docHeight))-range);
      objekt.css({"transform" : "rotateX(" + vert + "deg) rotateY(" +horiz + "deg)"});
      noTransition();
    }

    function reset() {
      body.removeClass("notransition").addClass("transition-reset");
      objekt.css("transform", "");  
    }


    doc.mousemove(function(e){
      x = e.pageX;
      y = e.pageY;
    });

    doc.mousemove($.throttle(50,followMouse));

    doc.on({
      mouseleave : function(){ reset(); },
      mousedown : function(){ reset(); }
    });
};

Check out the working example on jsfiddle: http://jsfiddle.net/Xw259/

Your assistance with this is greatly appreciated. Thank you.

Answer №1

It's kind of peculiar when each card becomes its own center but..

Code Example

You know, doing a bit of searching on Google before posting a question here could be beneficial....

Check out this link for more information

Anyway...

$(document).mousemove(function(e) {
    $('article').each(function(i,elem) {

        var xpos = $(elem).position().left;
        var ypos = $(elem).position().top;

        var cx = Math.ceil($(elem).parent().width() / 2.0);
        var cy = Math.ceil($(elem).parent().height() / 2.0);
        var dx = e.pageX - cx;
        var dy = e.pageY - cy;

        if (cardIsCenter) {
            cx = xpos + Math.ceil($(elem).width() / 2.0);
            cy = ypos + Math.ceil($(elem).height() / 2.0);
        }

        var tiltx = (dy / cy);
        var tilty = - (dx / cx);
        var radius = Math.sqrt(tiltx*tiltx + tilty*tilty);
        var degree = (radius * 20);

        $(elem).css('transform',
                    'rotate3d(' + tiltx + ',' + tilty + 
                    ',0,' + degree + 'deg)');
    });
});

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

Prevent onClick event in jQuery and extract parameters from a function call

We've been tasked with implementing a temporary solution to some code, so it might seem a bit silly at first. But please bear with us. The goal is to block the onclick method of an anchor tag, extract the parameters from the function call, and then u ...

What is the solution to the error "modal is not defined" in Vue.js?

Hey guys, I need some help with an error that popped up: [Vue warn]: Error in v-on handler: "TypeError: $(...).modal is not a function". The issue is with the modal function Below is the code snippet from my welcome.blade.php: <body> &l ...

In order to resolve this issue, I must eliminate any duplicate objects and then calculate the total sum using JavaScript

I have successfully removed the duplicates so far, but now I am stuck on how to sum the Total_Quantity. Is there a way to achieve this within the reduced method itself? Any help would be appreciated. Thank you. const test = [ { Item_Nam ...

Checking for app installation using jQuery AJAX across different origins

I am looking for a way to verify if a user has my app installed by using the protocol 'myapp://.' When a button is clicked, I want to check if the app is installed on the user's device. If it is, I would like to redirect the browser to the ...

Is it possible to add a personalized attribute to an HTML element with Jquery?

I'm looking to enhance an HTML tag by incorporating a custom attribute using jQuery. Here's my initial setup... <div class="module media object"> But what I aim to achieve is... <div class="module media object reveal-modal" id="obje ...

The export button in the React Material Table doesn't seem to be displaying correctly

[I am encountering an issue with the React export button in Material Table. The bar is not showing completely. My code includes the following: options = {{exportButton:true}} How can I resolve this?]1 ...

Error in test runner: Cannot convert type 'Cucumber' to type '? extends Runner' in Java cucumber

I'm currently working on setting up the Cucumber framework using Java for running my tests, but encountering a type mismatch error in the Test Runner. package cucumbertest; import org.junit.runner.RunWith; import cucumber.api.CucumberOptions; import ...

What is the best way to use jQuery to emphasize specific choices within an HTML select element?

Seeking help with jQuery and RegEx in JavaScript for selecting specific options in an HTML select list. var ddl = $($get('<%= someddl.ClientID %>')); Is there a way to utilize the .each() function for this task? For Instance: <select i ...

jQuery-powered transitions for seamless web page navigation

Despite the presence of similar inquiries on this platform, none seem to fully address my specific question... I have a 5-page static website designed to resemble the interior of a hair salon. I am interested in having each page transition simulate the us ...

What are the steps to implement $navigateTo() in a NativeScript Vue application?

What could be causing $navigateTo(Page) to not work? Visit this link for more information ...

Surprising results when a class is applied using jQuery

Exploring the differences between two fiddles (make sure to run the code on the jsfiddle pages to see the differences clearly). First Fiddle Simple demonstration: $("body").addClass("noScroll"); alert($("body").hasClass("noScroll")); $("body").removeCla ...

Is there a way to set up a local npm module directory without using symlinks

Here is a breakdown of the file structure in a simple way. /my-module ..package.json /my-app ..package.json I am trying to have my-app install my-module locally. This is what I have attempted: "dependencies": { "myModule": "../my-module" } The opti ...

Struggling with retrieving the $id variable from the view in both the controller and the database through Ajax

While checking my view, I noticed that the variable $id is visible. However, when I send it through Ajax, it ends up as NULL in the database. The way I'm sending the variable $id from the view using Ajax is like this: $.ajax({ url:'{ ...

JSON data utilized in Ajax request

I'm encountering an issue with displaying a value in an input field. Despite having successfully implemented this before, I am struggling to identify where my code may be incorrect. Within my HTML, I have an input field with the id="input" and a butt ...

What is the best way to vertically reposition two divs within the DOM using jQuery?

I need some help with this task. Here is the code I'm working with: <div class="one">You might also invite...</div> <div class="pic1"></div> <div class="name1">Some name</div> <div class="pic2"></div> & ...

Experiment with parsing multiple outputs instead of repeatedly coding them as constants in Node.js

In my application, I am parsing multiple database data using cron and currently, I have it set up to create a const run for each data to find the dag_id and manually test the determineCron function one at a time. How can I create an array so that the "dete ...

Terminal throws an error stating that no default engine was specified and no extension was provided

I have been working on executing a backend program in Node.js using MongoDB. I have created a form with two input fields for password and name. I am not utilizing any HBS or EJS and my VS Code terminal is displaying the following error: No default engine ...

Determined Worth of Chosen <Datalist> Option

Currently, I am utilizing an <input type='text'> Element in conjunction with a <datalist> to suggest user names for a form. The functionality is working correctly and all my users are displayed. However, upon form submission, I need ...

Adjusting the height of a textarea within a table

My textarea's height is supposed to be 500%, but it's not changing. I suspect that being inside a table might have something to do with the issue, but I'm unsure of what needs to be adjusted to set the height correctly. Surprisingly, the wid ...

How to make a Kendo Grid Combobox template or editor automatically set focus and select all text

I've been experimenting with using the combobox as either an editor or template for a column. The key difference is that one (the template) is always visible, while the other (the editor) is only displayed when the user edits a cell in the column. I&a ...