What's the issue with this fresh drag-and-drop directive clone?

Check out this jsfiddle where I used an angularjs directive to enable drag-and-drop functionality for a white square.

View Fiddle 1

In another version of the fiddle, I added a green square and duplicated the directive. However, the squares do not drag and drop as expected in this second jsfiddle. Can you help identify the issue in the code? View Fiddle 2

The changes I made were in the HTML section:

<div class="shapeX" ng-draggableX='dragOptions'></div>

In the CSS part:

.shapeX
{
    position: absolute;
    width : 40px;
    height: 40px;
    background-color: green;
}

And in the JavaScript section (where I duplicated the original directive and made necessary modifications):

.directive('ngDraggableX', function($document) {
  return {
    restrict: 'A',
    scope: {
      dragOptions: '=ngDraggable'
    },
    link: function(scope, elem, attr) {
      var startX, startY, x = 0, y = 0,
          start, stop, drag, container;

      var width  = elem[0].offsetWidth,
          height = elem[0].offsetHeight;

      // Obtain drag options
      if (scope.dragOptions) {
        start  = scope.dragOptions.start;
        drag   = scope.dragOptions.drag;
        stop   = scope.dragOptions.stop;
        var id = scope.dragOptions.container;
        if (id) {
            container = document.getElementById(id).getBoundingClientRect();
        }
      }

      // Bind mousedown event
      elem.on('mousedown', function(e) {
        e.preventDefault();
        startX = e.clientX - elem[0].offsetLeft;
        startY = e.clientY - elem[0].offsetTop;
        $document.on('mousemove', mousemove);
        $document.on('mouseup', mouseup);
        if (start) start(e);
      });

      // Handle drag event
      function mousemove(e) {
        y = e.clientY - startY;
        x = e.clientX - startX;
        setPosition();
        if (drag) drag(e);
      }

      // Unbind drag events
      function mouseup(e) {
        $document.unbind('mousemove', mousemove);
        $document.unbind('mouseup', mouseup);
        if (stop) stop(e);
      }

      // Move element, within container if provided
      function setPosition() {
        if (container) {
          if (x < container.left) {
            x = container.left;
          } else if (x > container.right - width) {
            x = container.right - width;
          }
          if (y < container.top) {
            y = container.top;
          } else if (y > container.bottom - height) {
            y = container.bottom - height;
          }
        }

        elem.css({
          top: y + 'px',
          left:  x + 'px'
        });
      }
    }
  }
})

Answer №1

Here is a simple adjustment to make:

<div class="shapeX" ng-draggableX='dragOptions'></div>

Change it to:

<div class="shapeX" ng-draggable-x='dragOptions'></div>

Also, update:

scope: {
  dragOptions: '=ngDraggable'
},

to:

scope: {
  dragOptions: '=ngDraggableX'
},

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

Is there a way to utilize req.query, req.params, or req.* beyond its original scope without the need to store it in a database?

Looking to streamline my code and apply the DRY pattern, I've been working on creating a helper function for my express http methods. The structure of each method is similar, but the req.params format varies between them. Here's how I attempted t ...

Display all attribute connections for a product in Prestashop

I have updated the products in my shop to include different combinations. These combinations involve a 'packaging' attribute with two options: a 100 units box and a 200 units box, each with its own unique reference number. On the product page, t ...

Implementing a custom button specifically for the month view in JavaScript FullCalendar

I have successfully added a custom button to my JavaScript full calendar code, but I would like this button to be displayed only in the month view. $(document).ready(function() { var calendar = $('#calendar').fullCalendar({ editable: tru ...

In React js, what is the best way to retrieve the first unique ID element as well as the last unique ID element from an

Hey there, I'm working with some data and you can find the link to it here: https://stackblitz.com/edit/react-26pgys. My goal is to filter the JSON and extract the first unique ID along with the last unique ID. I've already made an attempt at fi ...

Preserve the iframe src value in the dropdown menu even after the page is refreshed

I am trying to figure out how to prevent the iframe src from changing when I refresh the page, unless the user manually changes it using the dropdown menu with JavaScript. Can someone help me with this? <div class="row"> <div class="span9"> ...

Display a webpage once its design is completely loaded in Nuxt

I have implemented a layout for my admin pages that displays user information in a consistent format, eliminating the need to fetch this data every time the page reloads. However, I am facing an issue where the page does not wait for the layout to fully l ...

Implementing long polling for private messaging in PHP's chat functionality

Can you help me with a question I have regarding my chat form on the HTML page? Here is the code for the form: <form action="../addchat.php" method="POST" enctype="multipart/form-data"> <textarea id="textarea" style="border- ...

jQuery for Dynamic CSS Class

Is there a way to apply a different style to a link upon page load with jQuery? I would like the link to appear highlighted when the user navigates to a specific page, such as clicking on the About Us menu item. I want to use jQuery to achieve this effect. ...

Do we need to employ strict mode when utilizing specific ES6 functions in Node.js?

There has been a debate circulating at my workplace regarding whether or not it is necessary to include 'use strict' when using ES6 in Node.js without Babel. Some argue that certain ES6 methods may not function correctly without it, but I haven&a ...

How can I insert PHP code within the style attribute of a div tag?

I tried implementing this code, but unfortunately it's not functioning properly. My goal is to take user-defined width and height inputs in PHP and use them to generate a shape. echo "<div style='width:<?php $sirina?>;height: <?php $v ...

How can I incorporate classes from multiple CSS files into my WordPress theme?

Currently, I am utilizing wp_enqueue_style to incorporate two CSS files within a single function. However, the issue that arises is when I try to apply a class, it seems that only classes from one of the files can be utilized and it ends up overriding anot ...

What is the rationale behind allowing any type in TypeScript, even though it can make it more challenging to detect errors during compile time?

Why is it that all types are allowed in TypeScript? This can lead to potential bugs at runtime, as the use of type "any" makes it harder to detect errors during compilation. Example: const someValue: string = "Some string"; someValue.toExponentia ...

The true meaning of CSS3 transition is often misconstr

I'm trying to create a simple linear transition effect, but for some reason it's not working. Any suggestions on what might be causing the issue? HTML <div class="button-modern" style="background-color:#e73032"> <span style="color: ...

The issue arises when trying to use both CSS Sprite and Background Gradient simultaneously in Chrome/Safari

Lately, I've been having issues with the gradient not displaying correctly in Webkit, although it seems to be working fine in Firefox. Could someone take a look and see if there's an error in how I set it up? Please disregard the images, as it&ap ...

HTML5 enables the creation of an imperceptible scrollbar

I am looking to make my scrollbar invisible without it being visible however, I still want it to function when hovering over the box Also, I need it to work smoothly on both tablets and computers, which is why I have opted for using html5 I would great ...

Bootstrap Dropdown Functionality Malfunctioning

Here is a simple piece of HTML code that I have created: <!doctype html> <html> <head> <meta charset="utf-8"> <title>.:Home Page:. The Indian Sentinel</title> <link rel="stylesheet" href=" ...

ng-tourguide component for navigating through multiple screens

Currently, I am utilizing Angular JS to develop my project. One requirement I have is to implement a tour guide that navigates through multiple pages and displays the next step upon clicking the next button. I have successfully incorporated ng-walkthrough ...

Should I use React with Spring Boot or just Spring Boot for this project?

My partner and I are collaborating on a project for our current semester course. As we delve into our research on potential technologies to use, it seems like Spring Boot for the server side along with MySQL or Postgres for the database are emerging as s ...

Display a preview window once the image has been chosen

I have created an image preview div to show the selected image's thumbnail. Everything was working fine so far. But now, I want this div to be hidden when the page initially loads and only become visible when a user selects an image to upload. Here is ...

Encountering an issue when trying to download a PDF from an Angular 6 frontend using a Spring Boot API - receiving an error related to

When I directly call the Spring Boot API in the browser, it successfully creates and downloads a PDF report. However, when I try to make the same GET request from Angular 6, I encounter the following error: Here is the code snippet for the Spring Boot (Ja ...