Is it possible to move a directive within a limited parent element?

Is there a way to limit the movement of an angular.js drag directive within the confines of its parent element?

You can see the problem I'm facing in this jsbin: http://jsbin.com/maxife/3/edit?html,css,js,output

Answer №1

To achieve the desired outcome, it is necessary to make adjustments to the drag directive. The event.pageX and event.pageY properties indicate the position of the mouse pointer in relation to the left edge of the entire document. In order to attain this:

  • Modify these properties to be relative to the parent element.
  • Refer to this example for guidance: jQuery get mouse position within an element
    event.offsetX and event.offsetY will provide the position of the mouse click inside the span element:
<span my-draggable>Drag Me</span>
    This may not align with our objective, as you need to extract the height and width attributes of the parent element first and then use offsetX / offsetY for positioning within the parent div block.

How can this be integrated into the directive? Follow this reference: Get element parent height inside directive in AnguarJS

  • An alternative approach involves constraining the x,y variables within the mousemove function.
  • By doing so, movement will be limited to the boundaries of the parent element, preventing any overflow beyond the element using CSS.

    Here too, the height and width attributes of the parent element must be utilized, without altering the position or applying offsets. Simply include the following snippet before element.css({..}):

          if(x>27){
           x=27;
           }
          else if(x<0){
            x=0;
          }
          if(y>77){
            y=77;
          }
          else if(y<0){
            y=0;
          }
    

    I have demonstrated this manually to provide an example prior to incorporating the parent attributes. Take note of the span's width and height if you wish to prevent any part of the span element from extending outside the div.


    The complete module:

    angular.module('dragModule', [])
    .directive('myDraggable', ['$document', function($document) {
    return {
      link: function(scope, element, attr) {
        var startX = 0, startY = 0, x = 0, y = 0;
    
        element.css({
         position: 'absolute',
         border: '1px solid red',
         backgroundColor: 'lightgrey',
         cursor: 'pointer'
        });
    
        element.on('mousedown', function(event) {
          // Prevent default dragging of selected content
          event.preventDefault();
          startX = event.pageX - x;
          startY = event.pageY - y;
          $document.on('mousemove', mousemove);
          $document.on('mouseup', mouseup);
        });
    
        function mousemove(event) {
          y = event.pageY - startY;
          x = event.pageX - startX;
          if(x>27){
             x=27;
           }
          else if(x<0){
            x=0;
          }
          if(y>77){
            y=77;
          }
          else if(y<0){
            y=0;
          }
          element.css({
            top: y + 'px',
            left:  x + 'px'
          });
        }
    
        function mouseup() {
          $document.off('mousemove', mousemove);
          $document.off('mouseup', mouseup);
        }
      }
    };
    }]);
    

    View the JSbin here: JSbin link

    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

    Using expressJS and MongoDB to create a secure login and registration system

    I am interested in adding a login/register function to my expressJS API. Currently, I am only inserting the password and email into my database. I would like this function to first check if a user with this email is already in the database - if yes, then s ...

    Having trouble syncing a controller with AngularJS

    Despite numerous attempts, I am still struggling to make a single controller function properly. Lately, I've been working on Angular projects and no matter what I do, my controllers just won't cooperate. In my latest project, everything is withi ...

    An easy way to create a hover effect on a URL link and dynamically change the

    Is there a way to achieve the following? When hovering over various links, the image on the right changes. If no hover occurs, the default image will be displayed. https://i.stack.imgur.com/QXPXt.png ...

    I am attempting to utilize a ref in React to access an element within a MUI modal, but I am encountering issues as the reference to the

    I've been encountering an issue while trying to access the component did mount lifecycle method, as it's showing null. Interestingly, when I remove the modal, everything works as expected. However, inside the modal, the ref isn't functioning ...

    Reacting to multiple checkboxes in a check handling system

    In my latest project, I have designed a component that utilizes multiple checkboxes generated within a .map function. While testing the functionality, it came to my attention that users could select more than one checkbox at a time. This is not ideal as th ...

    Deselect a radio button with a click event using jquery

    When the page refreshes, radio buttons are left unchecked. <input type="radio" name="test"> 1<input type="radio" name="test">2 <input type="button" id="btn" /> $("#btn").click(function(){ $(':radio').each(function () { ...

    Solving template strings in a future context

    I have a unique use-case scenario where I am filling the innerHTML like this. However, my issue lies in resolving the template literal within the context of a for loop. Any suggestions on how to accomplish this? var blog_entries_dom = 'blog_entries& ...

    Eliminate JavaScript that blocks rendering:

    Currently, I am working on optimizing my website's speed and aiming for a perfect 100/100 score on PageSpeed Insights. The website in question is www.chrispdesign.com. Despite my efforts to relocate the code and make necessary adjustments, I have bee ...

    What functionality does this method perform within React.js?

    While going through the process of creating login forms, I stumbled upon this interesting method: handleChange(e) { this.setState({ [e.target.name] : e.target.value }); } I am a bit confused about the setState part in this method. The array brackets ...

    "Utilizing AJAX for real-time search to target the final

    Recently, I've been playing around with the AJAX Live Search feature that can be found on this site: http://www.w3schools.com/php/php_ajax_livesearch.asp The way it transfers the input value via AJAX to a php file for comparison is quite interesting ...

    Animating progress bars using React Native

    I've been working on implementing a progress bar for my react-native project that can be used in multiple instances. Here's the code I currently have: The progress bar tsx: import React, { useEffect } from 'react' import { Animated, St ...

    Single array returned by observable

    Issue: I am looking for a way to consolidate the multiple arrays returned individually into a single array. Solution: fetchAllRiders() { var distanceObs = Observable.create(observer => { this.http.get(this.API + '/driver/all').map(res = ...

    The selected element does not support the addition of setSelectionRange

    I have encountered an error while trying to add the "setSelectionRange" method to an input element that I selected using "getElementById". The error message states that "property 'setselectionrange' does not exist on type 'htmlelement'" ...

    Slide inside a div to move content

    Check out the script I've been experimenting with for bringing in a menu from the left: Demo Fiddle To make this work, the sliding DIV needs to not only appear on the left but also push the 'left panel' and 'right panel' accordin ...

    Can you explain the meaning of the code provided below?

    I'm having trouble understanding the functionality of this code snippet: .bind(this); (I copied it from the Zurb Foundation dropdown plugin) .on('mouseleave.fndtn.dropdown', '[data-dropdown], [data-dropdown-content]', function ( ...

    Why styled-components namespace problem in React Rollup build?

    I designed a "UI Library" to be utilized in various projects using ReactJS + TypeScript + styled-components and Rollup. However, I am currently encountering issues with conflicting classNames. I am aware that styled-components offers a plugin for creating ...

    Encountering an error stating "cloudinary.uploader is undefined" while attempting to delete media files from Cloudinary

    I'm currently developing a web application using express and node.js. In my project, I'm utilizing cloudinary for uploading media files. While uploading and accessing media works smoothly, I'm encountering an issue with deleting images from ...

    What is the most appropriate unit of measurement for creating a responsive design?

    I am a beginner in the world of responsive design and I'm currently figuring out how to properly layout plugins on a website when viewed on smartphones. Here's an example: @media (min-width: 568px) { .musicPlayer{ width:600px; height:320 ...

    Tips for centering links in the navigation bar on Bootstrap 5 when viewing in a small size

    I had previously inquired about customizing the Bootstrap 5 navbar in this post: Adjust navbar height to be smaller and I received some helpful answers. Thank you to everyone who responded. However, I now have a follow-up question: I am interested in ch ...

    Modifying the selected color of DropDownMenu List items

    Hey there! I'm currently trying to modify the color of a material-ui element that is selected, but I'm having trouble finding any resources on how to accomplish this. My goal is to switch this pinkish shade to a more soothing blue hue. Update: I ...