Dragging the mouse to move the DIV

I am struggling to implement a feature where a user can move a div left or right by clicking, holding, and moving the mouse. The goal is for the position of the div to follow the x position of the mouse while held down. I have seen solutions to similar questions before, but I am having trouble getting it to work in my specific case. To simplify things, instead of moving the div, I just want "hello" to display in the console when the mouse is moved while clicked. Any assistance on this would be highly appreciated.

var divEl = document.getElementById("div");

var down = false;

divEl.addEventListener('mousedown', function (event) {
    var down = true;
    console.log("true");
}, true);

window.addEventListener('mouseup', function (event) {
    var down = false;
    console.log("false");
}, true);


document.addEventListener('mousemove', function(event) {
  event.preventDefault();
    if (down) {

      console.log("hello");

    }
}, true);

Although I see "true" when clicking on the div and "false" when releasing the mouse, I am unable to get the "hello" message to display in the console as intended.

Answer №1

The variable was initialized within the callback function. Simply remove the var and it will work as expected:

const divEl = document.getElementById("div");

let down = false;

divEl.addEventListener('mousedown', function (event) {
    down = true;
    console.log("true");
}, true);

window.addEventListener('mouseup', function (event) {
    down = false;
    console.log("false");
}, true);


document.addEventListener('mousemove', function(event) {
  event.preventDefault();
    if (down) {
      console.log("hello");
    }
}, true);

To learn more about scope, visit the following link: var statement at MDN

Answer №2

Here is a code snippet that may be helpful for your project:

   var mousePosition;
var offset = [0,0];
var div;
var isDown = false;

div = document.createElement("div");
div.style.position = "absolute";
div.style.left = "0px";
div.style.top = "0px";
div.style.width = "100px";
div.style.height = "100px";
div.style.background = "red";
div.style.color = "blue";

document.body.appendChild(div);

div.addEventListener('mousedown', function(e) {
    isDown = true;
    offset = [
        div.offsetLeft - e.clientX,
        div.offsetTop - e.clientY
    ];
}, true);

document.addEventListener('mouseup', function() {
    isDown = false;
}, true);

document.addEventListener('mousemove', function(event) {
    event.preventDefault();
    if (isDown) {
        mousePosition = {

            x : event.clientX,
            y : event.clientY

        };
        div.style.left = (mousePosition.x + offset[0]) + 'px';
        div.style.top  = (mousePosition.y + offset[1]) + 'px';
    }
}, true);

Check out the JSFIDDLE link for more details.

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

Ways to modify the final sum exclusively for a single table

I am currently struggling to figure out how to calculate only the grand total of the first table using just one jQuery/JavaScript script. The code I am referencing is from: Below is the code snippet: <!DOCTYPE html> <html xmlns="http://www.w3 ...

Identifying the class of a clicked button using Jquery

Currently, I am experiencing an issue with my code $(document).ready(function(){ $(".follow-button").click(function(){ alert("asdf"); } }); <button class="follow-button" align="right" align="center"> Follow </butt ...

In a Next.js project, Typescript seems to be overlooking errors related to proptype definitions and function types

Greetings everyone! I am currently working on a project using TypeScript and have implemented various rules and elements. However, I am facing issues with type errors for functions and props. Essentially, when using any function, it is necessary to specify ...

Verify the form data before triggering the ajax call with just one click

Ensuring that all required areas are completed in a form is crucial. The form needs to be validated properly to either reject the request with a message showing what information is missing, or submit it successfully... The rejection process works well as ...

jQuery's on change event only fires once for database values

In my code, I have three select dropdowns identified by the ids first-choice, second-choice, and third-choice. <select id="first-choice" style="border-radius: 0; width: 100%;" class="form-control" name="area"> <option value="">-Select-&l ...

Unable to set the height for ul/div elements

I'm struggling to make my navbar appear when I click the "menu button". The div seems to be present in the code, but with a height of 0. Here's the relevant section of the code causing the issue. Any suggestions on how I can resolve this? var ...

A guide to successfully sending the 'onClick' function to a child component within React

In my coding project, I have developed a versatile Modal component that can be customized with different headers, bodies, and footers, as well as various arguments for the Reactstrap components. While I am using Reactstrap to create the Modal, the issue is ...

The browser sends a request for a file, the server then downloads a pdf, and finally, the

Here is the process I am trying to achieve: 1) A browser sends an ajax request to the server, requesting a pdf file. 2) The server downloads the pdf file and returns it for display. 3) The browser then displays the downloaded pdf in an existing iframe. Be ...

Nextjs is facing challenges in enhancing LCP specifically for text content

I've been trying to boost my LCP score by optimizing the text on my page, but it seems stuck and I can't figure out why my LCP isn't improving. Take a look at the screenshot: https://i.stack.imgur.com/xfAeL.png The report indicates that &a ...

Discovering nested routes in Ember.js through search functionality

I am currently working on implementing a search functionality within a nested route that shares a model. Below is an example of my code: The "Products" and "Search" functionalities return a JSON response. Router Market.Router.map -> @resource &a ...

Performing a Mongoose query using the "find" method on multiple fields at once

I am currently developing an API using Node.js, Express, and MongoDB for a product available in the market. Each product has a title, brand, image, quantity, and other details. Our goal is to allow users to search for products by both title and brand in a ...

react component fails to rerender upon state change

I am struggling with a React functional component that includes a file input. Despite selecting a file, the text in the h1 tag does not change from choose file to test. The handleChange function is triggered successfully. A console.log statement confirm ...

Tips for preventing focus/autofocus on the initial form input using bootstrap/jquery

I am currently working on updating an application that utilizes jQuery 3.4 and Bootstrap 3.4. A form has been added to the bottom of the page, but it has an unintended consequence of the browser focusing on the first input element (checkbox) within that fo ...

Interactive messages displayed based on cursor movement with jQuery

Seeking advice here. I need something similar to a tooltip, but not quite. My website has numerous links scattered around. When these links are clicked, they trigger an ajax form to load at the bottom of the page. Sometimes, the form can be located far dow ...

JQuery - Issue with setTimeout Function on Mouseleave Event

I am currently facing an issue with the script below. The goal is to display a div instantly when hovering over a specific area, and then make it disappear after a certain amount of time when leaving that area. Everything works perfectly, except if the mou ...

What could be causing VueJs2 computed properties to not update?

Check out this updated grid example from the official examples. In my application, I need to reposition the sortOrders array. created: function () { var vm = this; this.columns.forEach(function (key) { vm.sortOrders[key] = 1 }) ...

Error in Passport JS: Trying to use an undefined function

I've been struggling with debugging my code in Express and Passport. I've tried following solutions from others but can't seem to get it right. Any help or useful links would be greatly appreciated. Here is the error message along with the ...

Highcharts displaying black color after AJAX refresh

Struggling to implement real-time data visualization using Highcharts, I found myself tired of sifting through documentation and feeling confused. My solution involves using AJAX refresh. When the page initially reloads, my chart renders properly. However, ...

Ways to retrieve directory information in Next.js hosted on Netlify

Having trouble retrieving a list of directories in Next.js on Netlify. The code works fine on localhost, but once deployed to Netlify, an error is triggered: { "errorType": "Runtime.UnhandledPromiseRejection", "errorMessage": ...

JS implementing a listener to modify a Google Map from a separate class

Currently, I am in the process of migrating my Google Map functionality from ionic-native to JavaScript. I am facing an issue while attempting to modify the click listener of my map from a separate class. The problem seems to be related to property errors. ...