Move the div with jQuery

I am currently working on making a div draggable without relying on jQuery UI.

Here is the HTML code:

<div class="wrapper">
  <div class="toddler"></div>
</div>

And here is the script I have written:

$.fn.slider = function () {
$(this).on("mousedown", function () {
    $dragging = true;
});

$(this).on("mouseup", function () {
    $dragging = null;
});

$(this).on("mousemove", function () {
    if ($dragging) {
        $(this).offset({
            left: $(this).pageX
        });
    }
});
};

$(".toddler").slider();

You can view my work in this JSFiddle link.

However, despite my efforts, the code does not seem to be functioning correctly. Can anyone help me figure out what's wrong and how to make it work?

Answer №1

const draggableElements = document.querySelectorAll('.draggable');

draggableElements.forEach(element => {
    element.addEventListener('mousedown', (e) => {
        let offsetLeft = e.clientX - element.getBoundingClientRect().left;
        let offsetTop = e.clientY - element.getBoundingClientRect().top;

        function moveElement(e) {
            element.style.left = e.pageX - offsetLeft + 'px';
            element.style.top = e.pageY - offsetTop + 'px';
        }

        document.addEventListener('mousemove', moveElement);

        document.addEventListener('mouseup', () => {
            document.removeEventListener('mousemove', moveElement);
        });
    });
});

Usage:

const containers = document.querySelectorAll('.container');
containers.forEach(container => {
    container.classList.add('draggable');
});

Answer №2

Utilizing jqueryUI is highly recommended for smoother drag functionality. While it is possible to drag without it, the seamless experience that jqueryUI provides cannot be matched.

Here are some examples:

Link 1

Link 2

I advise integrating a drag plugin into your function to enhance its smoothness.

Function implementation:

$(function() {
$('body').on('mousedown', 'div', function() {
    $(this).addClass('draggable').parents().on('mousemove', function(e) {
        $('.draggable').offset({
            top: e.pageY - $('.draggable').outerHeight() / 2,
            left: e.pageX - $('.draggable').outerWidth() / 2
        }).on('mouseup', function() {
            $(this).removeClass('draggable');
        });
    });
    e.preventDefault();
}).on('mouseup', function() {
    $('.draggable').removeClass('draggable');
});
});

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

Top method for utilizing overlays

Is there a method to randomly select hex codes for specific colors? I want to replicate the design in this image through coding. Image Here is the code I have so far: HTML <div id="group"> <div class="sub red panel"> </div><!--su ...

Adjust the width of the element to match the size of the image within

My webpage features an image along with some accompanying metadata that I want to be centered on the page. I want the div holding the metadata to be the same width as the image. Here's an example: Unfortunately, I am unable to determine the image&apo ...

Executing a dropdown menu click event using PHP and AJAX

I need to display associated data when a user selects an option from a dropdown list. Below is the code for the dropdown list: <select class="op" name="emp" id ="tab4"> <option value="">--Select--</option> <?php foreach ...

How can you ensure that the execution of your code only moves forward after the successful completion of asynchronous requests in jQuery Ajax

I'm facing a challenge in optimizing the speed and functionality of my Ajax requests. Here's a snippet of the code I've been working on: function fetchData(dataArray){//dataArray is an array containing roughly 10 elements var resultArr[]; ...

Storing information in a file with jQuery

Currently, I am in the process of creating a website with jquery that allows me to easily edit images. I have implemented some interactive buttons for users to input information (such as "0" or "1") via their browsers. However, my main challenge lies in s ...

Ways to display jQuery values as HTML text

Trying to concatenate the HTML text with the values of item.certificate_name has been a challenge for me. I've experimented with various methods, but none of them seem to work. The specific line I'm referring to is where I wrote . I have alread ...

Setting up breakpoints for nested rows in Bootstrap can be achieved by utilizing the responsive

Currently, I am in the process of learning how to create a responsive website. One thing that has me puzzled is how to set the breakpoints for the content when the screen size changes. Here is what I am aiming to achieve: https://i.sstatic.net/DeyD0.png ...

Best practices for sending variables to an HTML page using nodemailer

I am interested in sending an email with an HTML template that includes dynamic data. For example, I want to include a unique id within a link on the page. Is it possible to insert dynamic data into HTML content when sending emails? If yes, I would apprec ...

Check if the div has been clicked, even if its child elements have also

Is it possible to check if both a div and its child are clicked using jQuery? $('div').click(function(e){ if(e.target.id == 'test') alert(e.target.id); }); I have a specific div with an id of #test in my HTML code, and wh ...

C# MVC - Enabling dynamic row addition in an HTML table with multiple fields consolidated into a single cell

Hello, I'm new to c# MVC and could use some guidance. Currently, I am utilizing an example from Matt Lunn (here) to dynamically add new items to a bound list within an HTML table. However, the issue is that all the new items are being added to the fir ...

The active class consistently adds new menu options without removing the previous ones

I am facing an issue with my menu where the active class does not get added to the new menu item when clicked, despite being removed from the previous item. Below is the code snippet: <div class="row text-center" id="side-menu"> <nav> ...

What could be causing the issue with my Angular integration with Jira Issue Collector to not function properly?

Looking to link the Jira issue collector with an Angular application I attempted something along the lines of Component.ts import { Component, OnInit } from '@angular/core'; import * as jQuery from 'jquery'; declare global { inter ...

Using jQuery to animate a div element with CSS3

After creating a loader using CSS3 and CSS3 Animations, I am looking to implement the actual loading function with jQuery based on a specified duration. For instance, setting it to load fully in 30 seconds. This is what I currently have: < ...

Is there a way to restrict the quantity of items that can be sorted in a sortable element (

I am facing an issue with a draggable element that is connected to multiple sortables using connectToSortable. My goal is to restrict the number of items allowed in each sortable container. While I can achieve this when dragging from one sortable to anothe ...

Generating RSS Feed on HTML View in Rails 4

I'm currently in the process of building my personal website using Ruby on Rails 4. One challenge I'm facing is trying to scrape Medium.com to display my Medium articles on my page. While the articles are showing up as intended, the RSS code is ...

Utilize jQuery to invoke an ASP page method from an HTML page

I have a static web page named index.html which includes text boxes for data input. My goal is to send this data to an ASP page called Default.aspx using jQuery/AJAX. I attempted the following: $.ajax({ url: "Default.aspx/GetData", ...

Aligning Divs in a Responsive Browser

In the following illustration, I am facing an issue with my responsive code. I have three sections named square1, 2, and 3, each containing a white div with text on top and an icon positioned absolutely. Everything works fine when the browser width is 920p ...

Adjust the color of a contenteditable div once the value matches

I currently have a table with some contenteditable divs: <div contenteditable="true" class="change"> This particular JavaScript code is responsible for changing the color of these divs based on their content when the page loads. However, I am now ...

How can we align images above one another in a responsive manner using Bootstrap 3?

Looking for assistance with aligning and overlapping images on top of another image in Bootstrap while maintaining responsiveness. I've attempted the following: HTML: <div class="container"> <div class="row"> <div class="col-lg-12"> ...

Obtain the identification of a div that was generated using jQuery

I have been struggling with two functions that don't seem to work as expected. The first function creates a div in the dom, and the second function is supposed to get the ID using getElementById(), but it's just returning null. I tried using $.D ...