Tips for moving a div away from the mouse cursor

Creating a landing page where I need my logo to move away from the mouse cursor in a specific direction, but it's currently moving randomly.

The page is built using HTML and I have the flexibility to utilize any open-source JavaScript library.

<!DOCTYPE html>
<html lang="en">
<head>
    <style>.container {
        margin: 0 auto;
        width: 300px;
        height: 300px;
        border: 1px #000 solid;
        position: relative;
      }
      .box {
        width: 50px;
        height: 50px;
        border: 1px #000 solid;
        position: absolute;
        right: 200px;
        background: red;
        transition: 0.5s;
      }
      </style>
  </head>
<body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <section class="container">
      <div class="box"></div>
    </section>

    <script type="text/javascript">
  $(document).ready(function(){
    $('.box').hover(function() {
    $(this).box;
    $(this).css('position','absolute').css('top', Math.random()*200 + 'px').css('left', Math.random()*200 + 'px');
    });
    });
</script> 
</body>
</html>

I'm looking for precise movement of the logo following the cursor.

Answer №1

To start off, utilize the getBoundingClientRect() method to obtain the position of the element in terms of left, top, right, and bottom.

Next, make use of the mouse coordinates to determine the closest edge and proceed to relocate the box accordingly.

Below is a demonstration illustrating how this can be achieved. Feel free to customize it as per your requirements.

Take a look at the operational snippet below.

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

Guide: Positioning the Icon in the Top Right Corner of the Image

Objective: The goal is to ensure that the expand icon is always at the upper right corner of the image, regardless of its size or the responsive design in place. Challenge: I have attempted to address this issue but have unfortunately been unsuccessfu ...

What is a clear indication that a <div> is filled with text?

Picture a scenario where a website contains an element that needs to be filled with random text using JavaScript. Once the div is completely filled, it should reset and begin again. It may sound odd, but the question is: how will the JavaScript determine w ...

I need assistance with incorporating a datepicker feature using jQuery UI

Can someone please assist me? I am trying to incorporate a datepicker (Jquery UI) and add an additional function in the script for counting, but my understanding of jquery is limited. (My English skills are also lacking, apologies in advance) I would dee ...

The toggleClass() function is only toggling between a single class

I'm currently facing an issue with a jQuery/Angular function that is triggered on click. <a ng-click="like()" href="#" class="like like--yes"></a> Essentially, my goal is to switch between the classes like--yes and like--no when the like ...

CSS/JS Label Positioner using Mootools, perhaps?

I have been tasked with incorporating a form into our website. It seems simple at first, but this particular form has some interesting JavaScript code in place to ensure that the label for each input field sits inside it. This is a clever feature, but unfo ...

Utilizing ASP.NET AJAX: Enhancing User Experience with ScriptManagerProxy for HTML Button Click Events

I am currently working on a solution for the following issue: Managing the client-side click event of a button - preventing postback if the JavaScript call returns false (e.g. onclick="js:return IsThisAllowed()") The JavaScript method will either return ...

Personalize the file button for uploading images

I have a button to upload image files and I want to customize it to allow for uploading more than one image file. What is the logic to achieve this? <input type="file" />, which renders a choose button with text that says `no files chosen` in the sa ...

Encountering a CSS problem while attempting to design a section featuring a background image

On this page, I have the login bar on the right and the footer at the bottom. I want a div to sit in the area currently occupied by the background image and fill it with the full background image. Currently, everything is wrapped in a wrapper and the back ...

Express.js experienced a 404 error when processing POST requests

When working with js and express, the route handler file looks like this: var express = require('express'); var passport = require('passport'); var authRoutes = App.route('authRoutes'); va ...

save choice in antd select in react js

In the process of developing a ReactJS project, I am utilizing the antd select component to display a list of companies. Upon selecting a company name, the users registered under that company will be shown. The attached video showcases the functionality fo ...

Suboptimal placement of second submenu in Navbar

This question is inspired by a discussion on Stack Overflow that you can read here. Everything seems to be working fine, except when the 2nd level item is not at the top. In the example provided, the item with the 2nd level menu is the first item. If you m ...

What are the steps to create custom Typescript RecursiveOmit and RecursivePick declarations for efficient cloning routines?

For some time now, I have been attempting to create a declaration for RecursiveOmit and RecursivePick in cloning methods such as JSON.parse(JSON.stringify(obj, ['myProperty'])) type RecursiveKey<T> = T extends object ? keyof T | RecursiveKe ...

Dropdown navigation with CSS

It seems like there's a simple oversight on my end... The drop-down menu I created is causing the main navigation bar to expand. You can view the page I'm working on by following this link. The issue occurs with the navigation below the App butto ...

Exploring the functionality of $timeout in AngularJS

Can you explain the functionality of $timeout in AngularJS and how it sets itself apart from traditional setTimeout()? ...

Error with displaying uib-datepicker within a table row

I need assistance with integrating a uib-datepicker into a table: <div class="table-responsive"> <table class="table table-striped" > <thead> <tr> <th class="col-md-2"><span>Date ...

Building a custom login page with axios in a react-redux application

I've encountered an issue with my login page. When I click the submit button, it does not redirect to the main Dashboard page. Check out the code below for authentication/login.js: import React, { Component } from 'react' import { Field, ...

What is the most efficient method for storing text in my web application?

Hey there, I'm looking for a way to easily store and access the wording used in my application so that I can use them again whenever needed. For example, loading messages, validation messages, or informational messages are some of the wordings I want ...

combine two JSON objects into a single object based on their unique identifiers

I am facing a challenge with two JSON objects that I have: Object 1: { "jcat":[ { "TITLE":"SEO", "ID":"27", }, { "TITLE":"Functions and Events", "ID":"2" }, ] } Object 2: { "job":[ { ...

Using Jquery to encase an element in a div while scrolling down and removing it while scrolling up

After some experimentation, I've managed to wrap an element inside a div using jQuery. My next challenge is to wrap it as you scroll down and unwrap it as you scroll up. Do you think this is achievable? Although I have succeeded in wrapping it while ...

Discover the size of objects in three.js

Looking for a way to determine the dimensions of a mesh in three.js? I have Collada (.dae) files and need to know their size in units (x,y,z). I've heard about using geometry.computeBoundingBox(), but could use more guidance on how to implement it. ...