"Drag and drop elements that automatically snap to a grid and move with

I'm trying to create a small, square div that follows the mouse cursor, but I want it to snap to a 3x3 pixel grid.

Here is what I have so far:

$(document).mousemove(function(e) {
  window.x = e.pageX;
  window.y = e.pageY;
  if(window.x % 9 === 0 ){
    $("div").css("left",window.x);
    $("div").css("top",window.y);
  }
});

However, the snapping isn't quite right and the movement is slow. Additionally, I need the pixel grid to align with a parent div container rather than the browser window size.

Answer №1

If you want to create a square shape, you can define the size by subtracting the width and height.

Here is a suggested code snippet:

UPDATE

$(document).mousemove(function(e) {
  demiSquareX = $(".inner").width()/2;
  demiSquareY = $(".inner").height()/2;
  windowX = e.pageX - $(".outer").offset().left - demiSquareX ;
  windowY = e.pageY - $(".outer").offset().top - demiSquareY;
  if(windowX<=0 || windowX >=($(".outer").width()-$(".inner").width()) || windowY <=0 || windowY >= ($(".outer").height()-$(".inner").height())){
      //out
  }else{
    if(windowX % 3 == 0 || windowY % 3 == 0){
      $(".inner").css("left",windowX);
      $(".inner").css("top",windowY);
     }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="outer" style="border:3px solid black;width:300px;position:relative;height:300px;left:100px;top:50px">
 <div class="inner" style="background:red;width:20px;height:20px;position:absolute"></div>
</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

Customize JQGrid columns by adding new columns at run time

I'm new to working with J Query and I'm experimenting with some samples on http://www.trirand.com/blog/jqgrid/jqgrid.html where I noticed that column names are written in JS and displayed in the Grid. My requirement is to show the Column they se ...

Is there a feature to enable a separate comment box for every tweet, similar to the toggle

Just starting out with jQuery and JS. Want to create a simplified version of Twitter with individual comment boxes for each tweet. Here's my JSFiddle: Currently, the comment box is appearing at the end of the last tweet instead of under each tweet. Ho ...

Classify the JavaScript objects according to the array of object lists

Struggling to find a solution for converting this list of objects based on the group array. The challenge lies in iterating through the group Array and applying the object to multiple places when there are several groups. Additionally, trying to disregard ...

Tips on deleting CSS comments from a CSS file

Currently, I am utilizing nextjs + reactjs. My objective is to eliminate all CSS comments from my existing css file. Despite using next-purgecss in order to get rid of unnecessary CSS code, the comments are still persisting. What could be the reason behind ...

Is there a way to send a promise resolve or reject from a function code within router.post() in Express?

Below is my code in express (node.js) router.post('/example.json', function (req, res) { // getFileInfo is a function to return an array return getFileInfo(req.body.fileList).then((array) => { axios({ method: 'post', ...

Including HTML attributes within a PHP script

Currently, I am working on developing a message to be displayed to the user after they have submitted the contact form using PHP. However, I am facing an issue with styling the message as intended, particularly with elements like bold text and line breaks ...

Enhance your website with Jquery-powered page transitions that can easily be linked for a

I have a client who has a specific vision for their website. To demonstrate the concept, I've created a demo which can be viewed here: She requested page transitions similar to those in the demo for the main content. I used jQuery to implement this ...

On iPhone, links located under a fixed-positioned div can be easily clicked

I am facing an issue on our mobile website where the footer with fixed positioning overlaps with a scrolling feed underneath it, causing the links in the feed to be clickable from the footer area. Footer CSS: .footer { position: fixed; bottom: 0; right: ...

Receiving a blank array upon calling res.json() in Node.js script

I'm facing an issue with my code snippet that displays all posts, including the username and display picture of each user. Everything seems to be working fine as the log output is perfect. However, I'm struggling to return this data as a JSON obj ...

Ensuring the accuracy of nested objects through class validator in combination with nestjs

I'm currently facing an issue with validating nested objects using class-validator and NestJS. I attempted to follow this thread, where I utilized the @Type decorator from class-transform but unfortunately, it did not work as expected. Here is my setu ...

What is the best way to activate the default action/event of an HTML link (anchor element)?

Is there a way to programmatically trigger the default action of an HTML link using JavaScript or jQuery? Essentially simulating a user click on the link. Simply using .click() does not seem to do the trick. $('#alink').click(); // nothing happ ...

selecting a div element with a label using the nth-child property

I recently discovered the CSS3 :nth-child() Selector and decided to create a sample Here is the HTML snippet: <body> <div> <label>dsdf</label></div> <div>seconddiv</div> </body> And here's the CSS par ...

Setting a variable for a JavaScript function to insert a video - a step-by-step guide

Here is a grid structure that I am working with: <div class="main"> <ul id="og-grid" class="og-grid"> <li> <a href="http://..." data-video="my-url" data-largesrc="images/1.jpg" data-title="Title" data-descript ...

Is there a way to ensure that the div of my template spans 100% in width and height?

I'm attempting to make my div 100% in size but I am having trouble achieving it. Here is my code: <template> <div> <Navbar/> <Calendar/> </div> </template> <script setup> import Calendar from &apos ...

Use jQuery to Toggle Between Excerpt and Full Content

I stumbled upon this link: Toggle Posts in wordpress using jquery, but unfortunately, it doesn't quite meet my needs. I have a custom post type and what I'm trying to achieve is having an excerpt with a "Read More" link that toggles or slideToggl ...

Differences in behavior of constructors when utilizing ES6 shorthand notation

ES6 introduced a new way to initialize objects with functions and properties using shorthand notation. // ES6 shorthand notation const obj1 = { a(b) { console.log("ES6: obj1"); } }; // ES5 var obj2 = { a: function a(b) { con ...

Find out which way the user is scrolling in your React js application

I'm struggling to determine whether the scroll event is moving up or down, and I haven't been able to find a solution yet. import React, { useState, useEffect } from "react"; import { Link } from "react-router-dom"; const Nav ...

Ways to retrieve the content from a textfield

Is there a way to retrieve text from a textfield in material UI without using the onChange method? It just seems odd that I would need to constantly track the value with onChange in order to use it for any other purpose. I decided to search for solutions ...

What methods can be used to construct components using smaller foundational components as a base?

Is there a more elegant approach to constructing larger components from smaller base components that encompass common functionalities, akin to an interface in the OOP realm? I'm experimenting with this concept, but it feels somewhat inelegant. Repor ...

What are the steps to create a dynamic Ajax Loading view?

I have encountered this situation multiple times, but unfortunately, I have not been able to find a simple solution or a website that explains the process and reasoning behind it. My goal is to create a container (div) that includes both a loading element ...