How can I reset the mousemove event in jQuery?

I need to create a mechanism where I can move a div by clicking on it, and then click again to stop the div in that position. However, encountering an issue when trying to move the div again as the mousemove event does not get activated. How can this be rectified?

$('.move_div').on('click', function() {                    
    $('html').on('mousemove', function(e) {
       var x = e.pageX - this.offsetLeft;
       var y = e.pageY - this.offsetTop;
       $('div').css({'top': y, 'left': x});
    });
    $("html").on('click', function() {
       $('html').off('mousemove');
    });
});

Answer №1

const element = '.move_adv';
let canMove = false;

$(function () {
    $('html').on('mousemove', function (e) {
        console.log($(this).width());
        if (canMove == true) {
            let x = e.pageX - $(element).width()/2;
            let y = e.pageY - $(element).height()/2;
            $(element).css({
                'top': y,
                'left': x
            });
        }
    });
});

$(element).live('click', function () {
    canMove = !canMove;
});

http://jsfiddle.net/6y24s/2/

The key concept involves maintaining the movable state of the div using a boolean.

Further enhancements to the code are desired.

Answer №2

Click here to access the fiddle. If you wish to preserve your code, simply include:

event.stopPropagation();

Answer №3

By clicking on the div, a mousemove handler is dynamically added to it. Subsequently, an event handler is attached to the document to remove any existing mousemove handlers upon click.
As you move the mouse, the div follows suit. On another click, the mousemove handler is removed. Upon clicking the div again, a new mousemove event handler is added, but the click event handler from the document promptly removes it.
Therefore, with each subsequent click after the initial two clicks, the mousemove handler is both created and destroyed simultaneously.

An alternative approach would be to use .on() instead of .live(). It's essential to note that .live() has been deprecated in JQuery 1.7.

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

Leverage the Power of Multiple Markers on Google Maps with API Integration

My project involves creating a WordPress site that displays one marker on a map and has a list of additional locations below it. I aim to remove the description under the map and replace it with a simple list of locations alongside markers on the map. ...

Layer added to map by Mapbox encountered an error during the process

I encountered an error that looks like this: https://i.sstatic.net/TI4HO.png When running the following code snippet: map.on('load', function () { map.addLayer({'type': 'scattermapbox', &ap ...

Passing data between Angular 2 components

Below is the component I am working with: @Component({ selector: 'myselector', providers: [ ], directives: [ ChildComponent], pipes: [ ], template: '<myselector>This is {{testEmitter}}</myselector>' }) export cla ...

Mastering the Art of Scrolling Down Content with Button Click in Ionic 3

I'm currently developing an Ionic chat application and I need the content to automatically scroll down when the user clicks on the send text button. You can see a visual representation of this in the images linked below. https://i.stack.imgur.com/gwR ...

`the issue of $scope object not being passed correctly to ng-if and ng-class ternary conditions

**app.js:** $scope.servers = [ {name:'SQL Server', status:"up"}, {name:'Web Server', status:"down"}, {name:'Index Server', status:"down"} ]; **index.html:** <table> ...

Designing a photo frame slider for a unique touch

My skills in javascript and jQuery are limited, but I am looking to create a customizable slider. While exploring options like Flexslider (), I found it challenging to meet the following specifications: Eliminate color gaps between thumbnails Enable thu ...

Navigating the implementation of undefined returned data in useQuery hook within Apollo and ReactJS

I am facing an issue with my code where the cookieData is rendered as undefined on the initial render and query, causing the query to fail authentication. Is there a way to ensure that the query waits for the response from the cookie API before running? co ...

Utilizing Props in Vue.js to Access Data for v-model

After browsing online, I attempted to pass props to data in the following manner: Child Component: props: { idInput: { type: String, required: false }, nameInput: { type: String, required: false }, }, data() { return { id: this.idInput, na ...

Looking to arrange an object by the value of a nested object in Typescript/Angular?

I'm currently developing an Angular 9 application focused on covid-19 cases, and I need to arrange my objects by the value of nested objects. Here is the dataset that I want to organize alphabetically based on the 'state' field values: stat ...

What is the best way to trigger a re-render of a component in React?

Currently, I am in the process of building my very first full-stack website. After a user signs in, their information is stored in the localStorage. The goal is to display the user's name in the header once they are logged in. However, my header is no ...

Text within the footer section

When displaying the name of a subcategory, I want it in one line. However, if the subcategory name contains two words, it should be displayed in two lines. https://i.stack.imgur.com/CcDeL.png Code: .Footer { width: 100%; display ...

Guide to adding files to a WordPress post with Selenium in Python

I attempted to automate the creation of WordPress post content using Selenium Webdriver (Python), but I encountered an issue with uploading files in the post content. Despite searching for a solution, most methods involved send_keys which is not suitable f ...

The Ajax call does not send the entire query

My issue lies with this ajax request $.ajax({ type: "GET", url: "/tracks/tweetaction?id=" + $("#artist_id").val() + "&link=" + url + "&message=" + prepopulated_tweet , success: function (data) { getPageLink(url); } }); The ...

Karma and RequireJS fetching files beyond the base URL

My goal is to set up automatic testing using karma with the following file structure: /assests /css /font /img /js /collection /lib /model /plugin /spec /view test-main.js main.js /templates index.html karma.conf.js In my ...

Overlaying diagonal lines/textures on a gradient or image background

Is it possible to achieve a similar texture/fill effect using only CSS? I am looking to overlay diagonal lines on top of various containers with different background fills, and I would prefer to avoid creating patterns as images if possible. Do you have a ...

Issues with POST functionality using jQuery and Express

I've done extensive research, but I haven't come across anyone facing the same issue as me. Currently, I am attempting to send a POST request using jQuery to my Express server. Here is my code: jQuery: $.ajax({ url: '/', typ ...

The initial attempt to use autocomplete with Jquery UI is not functioning as expected upon entry

I'm facing a frustrating issue that's driving me crazy. I'm not an expert in javascript, but I believe the solution is simple. I'm using jQuery UI autocomplete with data retrieved from Ajax. The problem is, I only get the desired resul ...

Filtering an array using criteria: A step-by-step guide

Currently, I am developing a system for Role Based permissions that involves working with arrays. Here is an example of the array structure I have: let Roles = { [ { model: 'user', property: 'find', permission: 'allow' ...

JavaScript influences CSS in EasySlider 1.7, creating a harmonious relationship between the

Struggling to achieve a captivating overlay effect with a slider using EasySlider 1.7, incorporating both images and corresponding text. However, encountering difficulties in aligning the text correctly on the page. The black overlay visible on the main s ...

Having trouble accessing the ID of a list item using jQuery?

Can you please help me figure out why the code below is not passing the list element ID to ajax correctly: Here's the HTML: <ul id="tree"> <li><a id="1">Finance</a></li> <li><a id="2">ACC& ...