Using JQuery to enable the movement of divs on a screen through clicking and dragging, without the use of

Recently, I've been experimenting with a small project involving draggable divs. However, the code I've written doesn't seem to be functioning properly, causing JQuery to become unresponsive.

Is there an alternative method that is simple and efficient for achieving drag functionality without using .draggable?

var hold = false;
        //Drag Elements

        $('#example').mousedown(function(){
            hold = true;
        });

        $('#example').mouseup(function(){
            hold = false;
        });

        $(document).on('mousemove', function(e){
            $('#example').css({
                while(hold){
                    left:   e.pageX-50,
                    top:    e.pageY-50
                }
            });
        });

Thank you!

Answer №1

Due to the single-threaded nature of Javascript, your while loop will never exit because the mouseup handler is unable to execute while you are still trapped in the mousemove handler.

To resolve this issue, simply switch out the while with an if statement:

$(document).on('mousemove', function(e){
    if (hold) {
        $('#example').css({
            left:   e.pageX-50,
            top:    e.pageY-50
        });
    }
});

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

Mastering the art of managing promises within nested loops

Embarking on my Promise journey, I find myself faced with a scenario where a list of objects within another list of objects needs to be updated based on responses from an external API. I've attempted to simulate the scenario below. The code snippet f ...

Learn how to utilize ng2-file-upload in Angular for uploading .ply files effortlessly!

I'm currently working on uploading various files using ng2-file-upload. I've been successful in uploading different file types like png and jpg, but I'm facing an issue with the .ply file extension. Can someone guide me on how to upload a fi ...

Exception being raised despite handling in JQuery AJAX post request

I am facing an issue with my login JSON service that handles username and password. When I make a call using JQuery 1.10.1 AJAX and input the correct credentials, it functions correctly. However, if I input incorrect credentials, the error function handler ...

When clicking initially, the default input value in an Angular 2 form does not get set

I am currently learning angular2 as a beginner programmer. My goal is to create a form where, upon clicking on an employee, an editable form will appear with the employee's current data. However, I have encountered an issue where clicking on a user f ...

Having trouble using $.post in jQuery AJAX with the .click() method?

I am experiencing some issues with my ajax request. It appears that the $.post method is not functioning as expected, as no request is being sent. There is also no information showing up in Firebug. Interestingly, I can make this code work: $('.c ...

I want to incorporate a smoother transition into my code

Can someone assist me in incorporating an easein effect into my animate function? I have included my code below. $('.img_left').animate({ 'margin-left' : '180px', 'opacity' : '1'}, 3000); Your help will b ...

Why does the event fail to trigger in an Angular 5 Kendo grid when the last character is deleted from the input box?

I have implemented a multi-filter in my Kendo Grid for an Angular 5 application. However, I am facing an issue where the event is not firing when the last character is deleted from the input box. How can I resolve this issue? For example, if I type ' ...

Position text on the background image without using positioning techniques

I need to center my text precisely on top of my background image without resorting to the use of relative or absolute positioning. Many solutions online rely on using absolute positioning for the text along with a specified top value, but I prefer not to e ...

Localhost is causing issues with Laravel in retrieving webfonts

I was trying to incorporate font-awesome into my Laravel project, but encountered a strange error. When I run the project, the following error appears in the console: GET http://localhost/fonts/vendor/@fortawesome/fontawesome-free/webfa-solid-900.woff2?5 ...

Having trouble integrating Bootstrap with Fullpage.js

After following this solution, I attempted to create a basic full-page layout using bootstrap. I aim to have a front end that scrolls like a full page, ensuring responsiveness. Folder Setup Code Snippet <!DOCTYPE html> <html> <head> & ...

implementing a fixed header in HTML

I am facing a challenge where I have a header with dynamic height and fixed position. My goal is to position the container div right below the header. However, since the header height varies, using a fixed value for margin-top is not feasible. Any sugges ...

Creating a series of image files from CSS and Javascript animations using Selenium in Python

Looking to convert custom CSS3/Javascript animations into PNG files on the server side and then combine them into a single video file? I found an interesting solution using PhantomJS here. As I am not very familiar with Selenium, adapting it for use with S ...

Utilize Javascript to create a function that organizes numbers in ascending order

Is there a way to modify this code so that the flip clock digits appear in ascending order rather than randomly? $( '.count' ).flip( Math.floor( Math.random() * 10 ) ); setInterval(function(){ $( '.count' ).flip( Math.floor( Math.rand ...

What steps should I take to eliminate the gap in my fixed bottom navbar?

I'm looking to revamp my menu layout by aligning the links with the social media icons and home button on the same line. The links are nested inside a div within the main navbar class (streetworn-demos), while the social media icons and homepage butt ...

What is the best way to conceal the broken image icon using PHP?

UPLOAD PICTURES IN DATABASE: if (!isset($_FILES['gambarid']['tmp_name'])) { echo ""; }else{ $rand5=rand(); $image_name5= addslashes($_FILES['gambarid']['name']); $fileext5=explode('.&ap ...

Optimizing WordPress with server-side AJAX caching

I am looking for a way to store AJAX responses on the server side rather than constantly retrieving data from the database every time a client makes a request. function post_filter($filter_action,$filter_values) { var ajaxurl = SiteInfo.home_url+&apos ...

Materriel-UI ToggleButton has the appearance of a traditional button

Looking to style a ToggleButton like a button? Having trouble with an error in the console when nesting a button inside? Check out this solution: const StyledToggleButtonGroup = withStyles((theme) => ({ grouped: { margin: theme.spacing(0.5) ...

Pass the array data stored in React state over to Node/Express

I have been exploring ways to transfer an array from my react front end to my node/express back end. Initially, I attempted the following method. In React: saveUpdates = (clickEvent) => { var list = []; var length = this.props.title.length; ...

Loading Kendo JS on the client side proves to be rather time-consuming

Working on my project, I have encountered a problem with the kendo ui scheduler where the downloading of the kendo js and css files on the client side is causing slowness on our website. To address this issue, we are attempting to download the kendo js and ...

What are the security benefits of using Res.cookie compared to document.cookie?

When it comes to setting cookies to save data of signed in members, I faced a dilemma between two options. On one hand, there's res.cookie which utilizes the Express framework to set/read cookies on the server-side. On the other hand, there's d ...