What is the best method for creating a draggable widget in HTML, specifically with the use of Angular?

I am searching for an HTML div that is free floating and can be dragged and positioned anywhere on the page without being affected by other elements. It's okay if the element blocks the view of elements below, and it would be great if there is a minimizing capability. Are there any libraries that offer this functionality?

After searching on Google, I only found items that can be dragged from one position and placed inside another. I couldn't find any free floating libraries.

Answer №1

To enable dragging functionality, you need to utilize the draggable attribute along with some JavaScript logic. Please note that the following code example uses pure JavaScript, not AngularJS.

function drag_start(event) {
  var style = window.getComputedStyle(event.target, null);
  event.dataTransfer.setData("text/plain", (parseInt(style.getPropertyValue("left"), 10) - event.clientX) + ',' + (parseInt(style.getPropertyValue("top"), 10) - event.clientY) + ',' + event.target.getAttribute('data-item'));
}

function drag_over(event) {
  event.preventDefault();
  return false;
}

function drop(event) {
  var offset = event.dataTransfer.getData("text/plain").split(',');
  var dm = document.getElementsByClassName('dragme');
  dm[parseInt(offset[2])].style.left = (event.clientX + parseInt(offset[0], 10)) + 'px';
  dm[parseInt(offset[2])].style.top = (event.clientY + parseInt(offset[1], 10)) + 'px';
  event.preventDefault();
  return false;
}

var dm = document.getElementsByClassName('dragme');
for (var i = 0; i < dm.length; i++) {
  dm[i].addEventListener('dragstart', drag_start, false);
  document.body.addEventListener('dragover', drag_over, false);
  document.body.addEventListener('drop', drop, false);
}
div {
  position: absolute;
  left: 0;
  top: 0;
  /* set these so Chrome doesn't return 'auto' from getComputedStyle */
  width: 200px;
  background: rgba(255, 255, 255, 1);
  border: 2px solid rgba(0, 0, 0, 1);
  border-radius: 4px;
  padding: 8px;
}

body,
html {
  min-height: 100vh;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div draggable="true" class="dragme" data-item="0">Drag me</div>

Answer №2

Experience a fantastic directive that will enhance your user interface. Check out its GitHub Link at... angular-dragdrop. You can find a Demo here

Take a look at the Sample Code:

HTML DOM:

<div class="btn btn-primary" data-drag="true" data-jqyoui-options="{revert: 'invalid'}" ng-model="list1" jqyoui-draggable="{animate:true}" ng-hide="!list1.title">{{list1.title}}</div>
<div class="thumbnail" data-drop="true" data-jqyoui-options ng-model="list2" jqyoui-droppable style='height:50px;'>
  <div class="btn btn-success" data-drag="false" data-jqyoui-options ng-model="list2" jqyoui-draggable ng-hide="!list2.title">{{list2.title}}</div>
</div>

JS:

App.controller('OverviewCtrl', function($scope) {
  $scope.list1 = {title: 'AngularJS - Drag Me'};
  $scope.list2 = {};
});

Answer №3

Have you explored JQuery's straightforward draggable feature? Check it out here: https://jqueryui.com/draggable/#default

If you want the div to float freely, simply add the following CSS:

position: absolute;

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

What could be the reason behind ejs not allowing if else statements when the variable is undefined?

I am attempting to replicate a rather simple example from this question here <div <% if (page_name === 'overview') { %> class="menu__menu-overviewPage menu" <% } %> class="menu"> However, when I try it on a ...

Discover the power of integrating JSON and HTTP Request in the Play Framework

My aim is to develop a methodology that can effectively manage JSON and HTTP requests. This approach will facilitate the transition to creating both a Webapp and a Mobile App in the future, as JSON handling is crucial for processing requests across differe ...

What is the importance of maintaining immutability for objects in Redux?

What is the importance of immutability in Redux? While I understand that frameworks like Angular2 use onPush to leverage immutability for quicker rendering of views, I'm interested in learning about other reasons why Redux emphasizes immutability desp ...

Is it possible to create separate layouts for mobile devices and tablets using jQuery mobile?

Currently building a jQuery mobile app and looking to implement two distinct designs/layouts, one for mobile devices and another for tablets. Is this achievable? If yes, how can it be done? Any specific code required? Cheers! Noah ...

What could be causing my canvas to not display my sprite?

Currently, I am in the process of learning JavaScript and experimenting with creating games to make the learning experience more enjoyable. However, I am facing an issue while using EaselJS and CreateJS to develop these games as a beginner. I need some as ...

Issue with uiRouter: values not being set upon state change

For some reason, I can't seem to retrieve the "personId" variable in the controller when changing states, even though it appears in the URL. I've tried everything but it always ends up being undefined. Hopefully, someone can spot the mistake - he ...

Show a popover within a parent div that has limited visible space due to its hidden overflow

Struggling with AngularJS, I can't seem to find a simple solution for this problem. In my code, there's a div element with the overflow: hidden property set due to an internal scrollbar. Inside this div, there's a dropdown menu that is trigg ...

Ways to create a transparent parallax background

Currently, I'm tasked with developing an educational website using HTML and CSS for a school project. Unfortunately, due to restrictions on code.org, I cannot utilize JavaScript files or script tags. Despite successfully implementing a parallax effect ...

Error: THREE.MTLLoader is not a constructor, version 3.0 bug uncovered

function loadModel(path, objName, mtlName) { var onProgress = function(xhr) { if (xhr.lengthComputable) { var percentComplete = xhr.loaded / xhr.total * 100; console.log(Math.round(percentComplete, 2) + '% downloade ...

Troubleshooting issues with mail subscriptions using Ajax and PHP

My Idea for Implementation I successfully set up a subscription form using PHP initially. However, I wanted to enhance the user experience by implementing an Ajax feature that would display a nice image and a "thank you" message without reloading the pag ...

Converting a Javascript object to JSON format only once using AngularJS

Is it possible to convert a JavaScript object to JSON using angular.toJson only once in my code? Here is an example: $scope.task.tags = [{"id":22,"tag":"printer","created_at":"2016-03-15" }]; $scope.create = function(task) { tmp.tags = angular.toJson( ...

Identifying Elements Generated on-the-fly in JavaScript

Currently, I am tackling the challenge of creating a box that can expand and collapse using regular JavaScript (without relying on jQuery). My main roadblock lies in figuring out how to effectively detect dynamically added elements or classes to elements a ...

An unusual occurrence with the setTimeOut function within a for loop was observed

When attempting to log numbers at specific intervals on the console, I encountered an unexpected issue. Instead of logging each number after a set interval, all numbers are logged out simultaneously. I've experimented with two different approaches to ...

What method can I use to locate the double quote option within an HTML select element using jQuery?

Here is an example of the select: <select id="id0" name="name0"> <option value='30" size'> 30" size </option> </select> The select contains double quotes. I am trying ...

Implementing coordinate formatting in JavaScript [Node.js]

I'm looking to tweak the JSON output into this specific format: [ 50.87758, 5.78092 ], [ 52.87758, 5.48091 ] and so on. Currently, the output looks like this: [ { lat: 53.1799, lon: 6.98565 }, { lat: 52.02554, lon: 5.82181 }, { lat: 51.87335, l ...

prevent unnecessary duplicate database queries for generating metadata in the upcoming 13 or 14 instances

In the latest updates, version 13 and 14 of Next introduced the usage of the generateMetadata function as the preferred method to define all page metadata. However, a drawback of this approach is that because of the separation of logic, fetching data base ...

Event that signifies a change in the global state of the Angular 2 router

Is there a universal event that can be utilized for state change/start across all components, similar to the Component Lifecycle Hooks ? For example, in UI-router: $rootScope.$on("$stateChangeStart", function() {}) ...

Display <tr> tag when button is clicked without refreshing the page

I have a specific requirement to hide a certain tag initially. If the user clicks the forward button without selecting any radio buttons or checkboxes, the tag should be displayed and the page should not refresh. However, there seems to be an issue with ...

Switching the visibility of multiple textareas from block to none

I am currently exploring ways to make one text area disappear while another one appears in its place. With limited knowledge of Javascript and just starting my journey into HTML and CSS, I am reaching out to the forum for assistance or guidance on the rig ...

Need to create a callback within a sequence of events?

Is it possible to create a callback chain like this? Widget.update(...).onUpdate(function(data){ console.log('updated'); }); Here is the current code snippet: var Gateway = {}; Gateway.put = function(url, data, callback) { $.ajax({ ...