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

What could be causing the error when trying to submit to OData Edm.Decimal type?

Having an issue submitting JSON to an OData service. The $metadata indicates it expects this format: <Property Name="curClaimValue" Type="Edm.Decimal" Nullable="true" Precision="19" Scale="4"/> This snippet is from my JSON data: ..."curClaimValue" ...

Bring in d3 from unpkg

Uncertain of which file to import, I am seeking guidance on how to import d3 from unpkg.com. Can someone advise me on the equivalent unpkg version of: import * as d3 from "d3"; ...

Clarification: Javascript to Toggle Visibility of Divs

There was a similar question that partially solved my issue, but I'm wondering if using class or id NAMES instead of ul li - such as .menu, #menu, etc. would work in this scenario. CSS: div { display:none; background:red; width:200px; height:200px; } ...

Preserving filter selections in Datatables and transferring them back to dropdown menus

I have implemented Jquery datatables with dropdown filters in the form of a table. The HTML structure is as follows: <table id="example"> <thead> <tr> <th>Name</th> <th>Position</th> ...

The Chrome file storage system saves information in files

My challenge is to save data obtained from the Chrome geolocation API into a text file using the Chrome fileSystem API. However, despite successfully creating a file, it remains empty after the process. To simplify, I attempted to add the string '1234 ...

What could be the reason behind the disappearance of text from the previously highlighted button in my calculator's "button grid" when I change the highlighted button?

Currently, I am in the midst of creating a tip calculator with a grid consisting of various percentage buttons. My main objective is to change the font and background color when any tip button is selected. Nevertheless, an issue has surfaced - whenever I h ...

Exploring the Differences Between Nth-CSS and Jquery

What are the advantages of using the nth function in CSS instead of applying it through jQuery, especially considering its compatibility with IE? Is it better to simply use jQuery from the start and avoid using it in a stylesheet altogether? Hopefully thi ...

Challenges with loading content and async JavaScript within websites

I decided to replace the content on index.htm with the content from project.htm. By clicking on a#front, it redirects to project.htm and dynamically updates the content. However, I am facing an issue regarding how to run the javascript that accompanies thi ...

The nodejs application seems to be encountering an issue as the /public/index.html file is not displaying on the

|project-name | client | public | index.html | server.js ↑ Structure of the Project The goal is to display the index.html file (located in the public folder) in server.js. [ server.js ] const express = require('express') const app ...

Calculating the number of items in the Ajax response list

Using jQuery to Count List Items $.ajax({ url : "/assets/inc/list.php", success : function (data) { console.log($(data).filter('li').size()); } }); By implementing the above code, I attempted to calculate the total number of ...

Setting up the Firebase emulator: should you use getFirestore() or getFirestore(firebaseApp)?

After delving into the process of connecting your app to the Firebase emulators like Firestore emulator, I came across the primary documentation which outlined the steps for Web version 9: import { getFirestore, connectFirestoreEmulator } from "fireba ...

Unique rephrased text: "Varied wrapping styles in both

Feeling frustrated with a seemingly commonplace issue. Despite the thousands of times it has been asked before, I can't seem to find an answer on Google. I wanted to neatly display my text within one of my cards, but so far I've only achieved th ...

Styling the scrollbar for the PDF element on an HTML page

I have a div that contains an object "linked" to a .pdf file. Is it possible to customize the scrollbar style using CSS or JavaScript/jQuery? <div id="container"> <object data="document.pdf" type="application/pdf" ...

Unusual spacing problem detected on iPad device

When I visit my demo site on my iPad, I'm having a strange issue where the player seems to be shifted to the top. This is how it looks on my iPad Mini running iOS 6.1 and tested on both Chrome and Safari: Here is the link to the demo site (change the ...

Tips for automatically inserting a "read more" link once text exceeds a certain character count

Currently utilizing an open-source code to fetch Google reviews, but facing an issue with long reviews. They are messing up the layout of my site. I need to limit the characters displayed for each review and provide an option for users to read the full rev ...

I have a quick question: What is the most effective method for creating PDF templates with Angular and .NET 6, specifically for designs that feature heavy

Seeking the optimal solution for creating PDF templates using Angular and .NET 6? Specifically looking to design templates that heavily feature tables. In my exploration of efficient PDF template creation with Angular and .NET 6, I ventured into using pdf ...

Tips for presenting random images from an assortment of pictures on a webpage

I'm looking to enhance my website by adding a unique feature - a dynamic banner that showcases various images from a specific picture pool. However, I'm unsure of how to find the right resources or documentation for this. Can you provide any guid ...

What is the best way to retrigger an ajax request in jQuery after it encounters an error?

In my JavaScript code, I have an AJAX request that communicates with a Rails controller to send data. If the controller detects duplicate information already in the database, it returns an 'Unprocessable Entity' error. I am looking to implement ...

Astro Project experiencing issues with loading SRC folder and style tags

After setting up a brand new astro repository with the following commands: npm create astro@latest npm run dev I encountered an issue where the default project template failed to display correctly on my computer. Here is how the page appeared: https://i. ...

How can I make text wrap instead of overflowing to ellipsis in a list when using vue-material?

Question: <md-list-item> <md-icon v-bind:style="{color: transcript.color}">account_circle</md-icon> <div class="md-list-item-text"> <p>{{ transcript.text }}</p> </di ...