What is the method for ensuring text remains within a square while it is being relocated?

Check out this jsfiddle where you can interact with a moving square:

http://jsfiddle.net/helpme128/3kwwo53t/2/

<div ng-app="test" ng-controller="testCtrl">
    <div id="container">
        <div class="shape" ng-draggable='dragOptions'></div>
    </div>
</div>

I'm looking to have the word "Square" appear next to the white square and move along with it. Is that even possible? If so, I'd love to know how to achieve this effect.

Answer №1

You have the ability to achieve this by inserting a span that is absolutely positioned within as shown below:

angular.module('test', [])

.directive('ngDraggable', 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'
        });
      }
    }
  }

})

.controller('testCtrl', function($scope) {
  $scope.dragOptions = {
    start: function(e) {
      console.log("STARTING");
    },
    drag: function(e) {
      console.log("DRAGGING");
    },
    stop: function(e) {
      console.log("STOPPING");
    },
    container: 'container'
  }

});
#container {
  width: 300px;
  height: 300px;
  background-color: black;
}
.shape {
  position: absolute;
  width: 40px;
  height: 40px;
  background-color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="test" ng-controller="testCtrl">
  <div id="container">
    <div class="shape" ng-draggable='dragOptions'><span style="position:relative;left:100%;top:0;color:red">hi</span>
    </div>
  </div>
</div>

Answer №2

An efficient approach is to utilize a pseudo-element:

.shape:before {
   content: "Box";
}

By doing this, it inserts specific content (such as the word "box") before the .square element within the DOM structure.

Answer №3

You have the option to utilize an uncomplicated method

{
    info: "Cube"
}

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

Where could one possibly find the destination of the mysterious <circle>?

I want to implement a simple pulsating animation on a circle svg element. I attempted using a transform: scale(..,..) animation, but it seems to be shifting the entire circle within its container instead of just scaling the element itself. This is the cur ...

Arrangement of asymmetrical interactive forms

I am in need of creating a design featuring numerous non-rectangular shapes that are interactive and reveal an image when clicked. The concept is to transform an image of stained glass into a webpage where each pane can be clicked to unveil its colorful ve ...

What common problems arise from using mutable data types in a single-threaded environment?

In JavaScript, concurrency is modeled by an event loop, eliminating race conditions. Given this, what are the potential downsides of performing a type-safe operation in the main scope of a program that would warrant caution? const m = new Map([["foo", tru ...

Customizing Background Color of Bottom Tab Content Container in React Native

Hey there, I need some help with changing the color of the bottom tabs screens. They are currently gray by default (as shown in the image) and I want them to be white. I've tried using tabBarStyle but it doesn't seem to work. If anyone has any i ...

"Utilize gulp-connect to store the root as an array

The gulp-connect documentation mentions that options.root can accept either an array or string. My situation involves having a build directory that I want to use as the root, along with a separate sources directory where all my source maps are located. Is ...

Tips for creating a clickable title that directs to a URL

I am currently using the "Import All" WordPress plugin to bring in an Excel file containing numerous hyperlinks that point to specific Custom Post Types and a designated field. These hyperlinks are separated by commas from the corresponding title. For exam ...

When I access the browser, it displays "???"" symbols instead of UTF-8 characters

When I view the website in my browser, it displays "???" instead of UTF-8 characters. How can I identify the cause and rectify this issue? Below is the content of the HTML file: <HTML> <title>Search Engine</title> <form ac ...

How to set the value of an `<input type="date"` in jQuery

Having trouble figuring out why this code isn't functioning properly. The input field I'm using is a simple 'input type="date"' setup like this.... <input type="date" name="Date"/> I am attempting to have the value automatically ...

Error in executing Javascript function

Below is a Javascript function I created for expanding and collapsing content: function showAns(inp){ var hide="#hideAns"+inp; var show="#showAns"+inp; var ansdiv ="#ans"+inp; $(hide).click(function(){ $(ansdi ...

Loss of value in .net Jquery CheckBox onchange event

My JQuery code for CheckBoxes is causing some unexpected behavior: $(document).ready(function () { $('#chk_AGVS').change(function () { if ($(this).is(":checked")) { '<%Session["chkAGVS"] ...

The present user who is currently logged into the stackmob platform

I am currently working on retrieving a list of contacts for the logged-in user, but I am struggling to identify the current user. In Parse.com, you would use Parse.User.current(), but I am unsure if Stackmob offers a similar functionality. Below is the co ...

Steps for resetting data() on a route without parameters:

Having trouble restarting a route on a new editor I have a specific route /editor as well as /editor?_id=dasd448846acsca The /editor route consists of a simple form with empty inputs, while the /editor?_id=dasd448846acsca route has the same component bu ...

What is causing this image to be off-center both vertically and horizontally on the table?

Currently, I have a small 20px by 20px image displaying in the top left corner of an empty table: <table width="100px"> <tr> <td width='100%' align='center' valign='center'> <img i ...

Custom positioning of Mui Snackbar in V5

I've been attempting to position a Snackbar in the top right corner with some customization for the top property, but I'm struggling to get it to display correctly. Here's what I've tried: import React from "react"; import { ...

How to Extract a Link from JSON Data in React Native

My JSON data is formatted like this: orderData:"<p>Key VVV: 6326233</p> <p>Download link <a title=\"Movie\" href=\"https://play.google.com/store/movies/details/The_Angry_Birds_Movie_2?id=O_RbjOHHpIs&hl=en\" t ...

Tips for avoiding infinite re-render loop when updating state in React/Next.js

I currently have a unique Next.js application that showcases randomly selected YouTube videos. The state within the app is structured as follows (managed by Redux): const state = { entities: { videos: { 'vidId1': { ...

Utilizing AngularJS ngResource: Ensuring Consistent Use of the Catch Function

Each time a server request using any $resource fails, I want to display the same alert message to my users. Currently, my code looks like this: function tryAgain() { alert("try again") } myResource.query().$promise.catch(tryAgain); myResource.update(...) ...

I can't quite understand the reasoning behind why this specific function is designed to output

I've been working on a JavaScript exercise and struggling to understand the logic behind it. The exercise involves a function named "mystery" that utilizes several basic functions to return an array in reversed order. Despite spending hours trying to ...

Having trouble getting tailwind dark mode to work on next.js?

I have set up a custom boilerplate using next.js(10.0.5) with preact(10.5.12), typescript(4.1.3), and tailwind(2.0.2). I am attempting to incorporate a dark mode feature from Tailwind. I followed the instructions from next-themes in order to add the dark ...

Sending a property as a parameter to a different component through Vue's router-link

I have a component designed to showcase recipes in a list format. Each recipe is rendered using a separate component from an array of recipes. I am currently attempting to pass the recipe object from one component to another component using Router-Link ...