Spin the div towards the location of the mouse

Is it possible to create a rotating effect on a div element based on the position of the mouse pointer?

I envision the div displaying <- when the mouse is on the left side, and -> when the mouse moves to the right, regardless of direction.

If anyone has a solution for this dynamic rotation effect, I would greatly appreciate any help!

EDIT:

<style>
    body {
        height: 100vh;
        display: flex;
        align-items: center;
        justify-content: center;
        overflow: hidden;
    }
</style>

<div id="arrow">&gt;</div>

<script type="text/javascript">
    var arrow = document.querySelector("#arrow");
    var arrowRects = arrow.getBoundingClientRect();
    var arrowX = arrowRects.left + arrowRects.width / 2;
    var arrowY = arrowRects.top + arrowRects.height / 2;

    addEventListener("mousemove", function(event) {
        arrow.style.transform = "rotate(" + Math.atan2(event.y - arrowY, event.x - arrowX) + "rad)";
    });
</script>

Answer №1

To track the mouse movement and adjust the arrow's rotation, you can utilize the following technique.

function determineCenter(element) {
    const {left, top, width, height} = element.getBoundingClientRect();
    return {x: left + width / 2, y: top + height / 2}
}

const pointer = document.querySelector("#pointer");
const pointerCenter = determineCenter(pointer);
addEventListener("mousemove", ({clientX, clientY}) => {
    const angle = Math.atan2(clientY - pointerCenter.y, clientX - pointerCenter.x);
    pointer.style.transform = `rotate(${angle}rad)`;
});
html  {
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
}
<div id="pointer">&gt;</div>

Answer №2

An adaptation using jQuery inspired by metarmask's solution.

var arrow = $('#arrow');
var arrowX = arrow.offset().left + arrow.outerWidth(true) / 2;
var arrowY = arrow.offset().top + arrow.outerHeight(true) / 2;

$(document).on('mousemove', function(event) {
  var rad = Math.atan2(event.pageY - arrowY, event.pageX - arrowX);
  arrow.css('transform', 'rotate('+rad+ 'rad)');
});
body {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="arrow">&gt;</div>

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

Does anyone know if it's feasible to return a value from PHP to an HTML form without relying on JavaScript?

Currently, I am in the process of learning how to create a basic web form. My goal is to develop an HTML web form that sends a number to PHP and then displays the number in another text field without refreshing the page. After doing some research online, ...

Copy and paste content from Outlook, Word, or any Office software directly into the embedded browser

Our application is performing well, but there is an issue with some users copying text to Word before pasting it into the app. The HTML gets parsed out somewhat correctly, but it often includes tags from outlook or word that our XHTML engine doesn't r ...

Use jQuery to apply a class to some input elements when certain events like keyup or

If I type something in the input field, it should add a border to the li tag containing the text. The current script works fine, but is there a way to make this jQuery script shorter? Thank you for your help! .add_border{ border: 2px solid #000 !impor ...

Guide to ensuring the navbar remains at the top of the webpage following an image

I am attempting to create a sticky navbar that stays at the top of the page once the header has been scrolled past. It should have a similar effect as shown in this example on codepen.io, but with the addition of an image that stretches across most of the ...

Developing Angular 6 for dynamic HTML navigation tabs

Being new to Angular 6, I recently created tabs in HTML and now need to convert them into Angular 6 while also making them dynamic. Here is the original HTML code: <ul class="nav nav-tabs side_nav" role="tablist"> <li role="presentation" class= ...

Activate an iframe upon changing the media query

I am currently working on a webpage where I have included an image within an iframe. I am looking to change the content displayed inside the iframe based on different media query breakpoints. For instance, if the viewport has a minimum width of 900px, I ...

Conflicting jQuery links arise when utilizing version 2.1.4 of jQuery

I have encountered a conflict with the jQuery link while using the LIMITLESS theme. Can someone please assist me in resolving this issue? <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script> The conflict is ...

Creating a dynamic table accordion with PHP and MySQL

I am currently working on creating an accordion table to display data retrieved from a database. I want the description data to be shown in a row below when clicking on the respective row. Despite my efforts in modifying various code snippets that I have c ...

Adding data from a database into an object in PHP for temporary use during the loading process can be achieved by following

I'm a beginner in PHP and I have some code that retrieves category type data from a database. I want to temporarily store this data in a PHP object while the page is loading. Initially, I need to load all predefined data and then use it when a certain ...

What is the best way to customize the appearance of an Angular tree component?

I'm attempting to incorporate the style of the ACE Admin theme into the angular-tree-component. Currently, my tree looks like this: https://i.sstatic.net/ktiEf.png However, I desire to apply styles from the Angular tree guide in order to achieve a ...

Seeking assistance in developing a dynamic footer complete with a gallery of images

Attempting to create a footer packed with images but struggling to ensure it looks good on both PCs and mobile devices. The goal is to align the bronze sponsor kitten to the left, and supporter kittens to the right, while keeping the footer at a reasonabl ...

What is the best way to display the time of a post update similar to the style of

I am currently working on creating a notification deck. Instead of displaying the time when a notification was received, I aim to show the time that has passed since its arrival similar to how Twitter and Facebook do it with formats like "32m" or "1 hour a ...

Is it possible to clear/reset the file input when the page is loaded?

One of my tasks involves clearing a file upload input field when the page is loaded. I've searched through 10-15 different ways on stackoverflow to accomplish this, but every solution requires a reset button which doesn't meet my requirement of a ...

What are some practical ways to incorporate JQuery into a ReactJS project?

Exploring the world of ReactJS for beginners, I am faced with a challenge. I have created a navigation bar that should stick to the top of the page when scrolled past 100px. Here is the code for my navigation bar: Navigation Bar Component Code: export de ...

The website created with Mobirise's HTML is experiencing display issues after being uploaded to NGINX through PuTTY

Recently, I embarked on building a website using NGINX but realized it needed a major revamp. That's when I turned to Mobirise as my HTML expertise is limited. Here's the initial site I created: https://i.stack.imgur.com/IsCg4.jpg However, upon ...

Having trouble getting padding to work inside a pre block, even when using a wrapper div?

Snippet of HTML Code: <div class="prewrap"> <pre> stepsize = .01 samplestimes = 30 universex = seq(-1, 1, stepsize) universey = sin(pi * universex) </pre> </div> Sample CSS Styles: #prewrap { background-color: #e3e3e3; pa ...

Engage in intricate animations on Blaze

Currently seeking an effective method for implementing animations within my app using Blaze. To provide further clarification, I have included a basic example below: <template name="global"> <h1>Hello everyone!</h1> {{> foo}} ...

Looking to style a <p> element with CSS?

In the div class index, there are two additional divs without any class or id names, along with two <p> tags. My goal is to style these two <p> tags. <div class="doubt"> <div> <p>Hello world</p> <div> ...

Troubleshooting strange behavior with Silex and Twig CSS caching issues

I'm facing a frustrating issue where changes I make in my CSS file are not reloading properly. The style.css file in PhpStorm appears as: body { background-color: blue; } However, when viewed in Chrome it shows: body { background-color: green; ...

Transform JSON into CSV format and save the file for download

My task involves fetching a JSON object from a URL and converting it to a CSV file for download by the user. I need to create a button with an onClick function that will call the API, retrieve the JSON object, convert it to CSV, and enable the user to down ...