Attempting to insert a square-shaped div within a larger square-shaped div and enable it to be moved around by dragging

Imagine this scenario: I have a button and a large div. When the button is clicked, the code adds a new div inside the larger one. However, the new div is not draggable because I didn't implement the necessary code.

I'm also trying to figure out a way to prevent the newly added divs from stacking on top of each other in a linear fashion. Ideally, I'd like them to appear in random positions within the container div.

Here's the current progress

Answer №1

Your library references are not aligned. I have made adjustments from:

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"</script>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>

to:

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.24/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.24/jquery-ui.min.js"></script>

It appears that there was a discrepancy in the libraries being loaded duplicated. The issue should be resolved after making these modifications.

Answer №2

Your JSBin has been updated and the libraries have been sorted out. I have made some changes to get you started on your project.

Make sure that your container, identified as #box, is positioned relatively as the draggable plugin requires the new boxes, marked as .new_box, to be positioned absolutely. Check the CSS for more details.

Here is the updated JavaScript code:

$(document).ready(function () {
  function createBox($parent, left, top) {
    var $box = $('<div class="new_box">Hello world</div>');
    $box.appendTo($parent);
    $box.draggable({
      containment: $parent,
      grid: [10, 10]
    });
    $box.css({
      left: left,
      top: top
    });
  }

  $(".add").click(function (e) {
    var $container = $("#box"),
        w = $container.width(),
        h = $container.height();

    createBox($container, Math.random() * w, Math.random() * h);
  });
});

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

Obtain the dimensions (width and height) of a collection of images using Angular and TypeScript

Currently, I am facing an issue with my image upload functionality. My goal is to retrieve the width and height of each image before uploading them. However, I've encountered a problem where my function only provides the dimensions for the first image ...

Enhance the appearance of your Vuejs application with conditional style formatting

I want to enhance a basic table by applying conditional CSS styles to the cells based on their values. For example: If area1 == 'one', then assign the td-one CSS style. <tr v-for="version in versions" :key="version.id"> < ...

What could be causing my Angular code to submit back unexpectedly?

My goal is to make an initial call to the database to populate some dropdowns, after which all actions are done through AJAX. However, whenever I click a button on the page, it seems to be posting back and calling the function that fetches dropdown values ...

What is the best way to distinguish if users are accessing my Facebook app through an iframe or by directly entering the

If my Twitter app url is http://tw.domain.com/ and the app url is http://apps.twitter.com/demoapp/ I need to ensure that users cannot access the application url directly, they must view it within an iframe on Twitter. What method can I use to detect & ...

ReactJS form submissions failing to detect empty input values

My goal is to use react to console.log the input value. Below is the code I've created: import React from 'react'; import ReactDOM from 'react-dom'; class App extends React.Component{ constructor() { super(); this.proce ...

Enhancing BarGraph and Bars Size in Oracle ADF

We have created a web application using Oracle ADF. The application includes a page with a graph displayed below. Currently, we are looking to enlarge the bar graph by increasing its height, width, and size of the bars themselves. Difficulty 1: While we ...

Steps to connect two drop-down menus and establish a starting value for both

In the scope, I have a map called $scope.graphEventsAndFields. Each object inside this map is structured like so: {'event_name': ['field1', 'field2', ...]} (where the key represents an event name and the value is an array of f ...

Develop an XML document with the use of either Javascript or PHP

I have an XML file that contains information about bracelets with photo details. <bracelets> <photo filename="b1.jpg" thumbnail="a1.jpg" description="aa" /> <photo filename="b2.jpg" thumbnail="a2.jpg" description="aa" /> & ...

What is the best way to create a global variable using jQuery?

Is it possible to pass the value of a_href = $(this).attr('href'); function globally and set a_href as "home"? var a_href; $('click a').on('hover', function(e){ a_href = $(this).attr('href'); ...

Can transitions be applied to links in this manner?

Having an issue with ajax requests, I am currently resorting to using JavaScript linking. This is how I normally link: window.location.href = ('file:///android_asset/www/custom/kontakty.html'); I am curious if it's possible to add a transi ...

Is there a foolproof method to authenticate form submissions using Javascript/Ajax instead of relying on PHP?

Currently, my process of handling HTML form submissions is done in PHP where I submit the form to a PHP file that: Verifies against a cookie created at page load to prevent CSRF. Includes a require_once() function for validation purposes. Executes other ...

You cannot use a relative path when inserting an image tag in React

I am having an issue with my img tag not loading the desired image when using a relative src path in my React project. When I try: //import { ReactComponent } from '*.svg'; import React from 'react'; import firebase from "./firebas ...

The second entry is not being styled by CSS, is there an issue with the code in this section?

I am facing a challenge while trying to set the same background image for two div elements: .abc { background: url('images/autogen.png') no-repeat 0px -133px; width: 256px; height: 256px; }; .def { background: url('images/autogen.png' ...

The issue of Jquery not functioning properly within Ajax-included HTML documents

I've tried looking at some other posts, but I couldn't understand them. The jQuery works fine when the page is loaded, but when the same elements are loaded from an AJAX script, the jQuery doesn't work. I know I need to do a callback, but ca ...

I am trying to dynamically load a div using Ajax, but whenever I do so, the position of the div changes. Is

I'm currently experiencing an issue with the function I'm using to refresh a section of my webpage. It seems that the ul#bla is being loaded twice, causing the list to shift position to the right. Is there a way for me to use this function to re ...

Utilize Vue: Bring in the router within a helper class and navigate to a specific

I'm new to utilizing Vue, and I am currently attempting to import my existing router instance into a JavaScript class where I manage the Authentication. This is the content of my router file: import Vue from 'vue'; import Router from &apos ...

Customizing Bootstrap Navigation: Creating Space Between Menu Items

I've configured my Bootstrap navigation with a dropdown toggle for "Coverage". I'm looking to decrease the spacing between each list item (li) under this dropdown. What CSS setting should I use to achieve this? Interestingly, when I apply float: ...

Presenting JSON information in a concise and visually appealing manner

How can I extract a value from JSON data and display it in an HTML text field? The JSON data looks like this: {"name":"paul"}, but I only want to display "paul" in my text field. Here is my code in CodeIgniter PHP: $data['name'] = $this->name ...

Both the maxlenght and ng-maxlength directives appear to be ineffective in AngularJS

In my HTML file, I have the following input: <input name="password" id="newPasswordConfirmation" ng-model="newPasswordConfirmation" type="number" inputmode="numeric" placeholder="" required ...

Is it possible to stack images on top of each other on a webpage?

I'm looking to create a dress-up game website where users can click on different accessories to layer them on top of each other. It's a bit tricky to explain, but I've found some examples that demonstrate what I have in mind: This site is ...