JQuery Resizable: A guide on creating multiple resizable divs that can be adjusted individually

I have created a basic web application that allows you to dynamically add div elements to a container div.

You can preview the app here:

Before resizing

https://i.sstatic.net/X2o6K.png

When you click the "Image" link in the left menu, a new div with a black background is added to the container div.

These dynamic divs can be dragged and resized using jQuery's draggable and resizable methods from jQuery UI library.

The draggable functionality works fine, but the resizable feature seems to cause dependency between the divs. When trying to resize one div, it affects the size of other dynamically added divs.

Here is an illustration of the issue I'm facing:

After resize https://i.sstatic.net/1J4Ot.png

As shown in the image, attempting to resize "div2" also resizes "div1" because of their interdependence.

I aim to make each div independent so they can be resized individually without affecting others even if they overlap.

Below are my code snippets:

<!-- JavaScript code block -->
      // Sample JavaScript code here
    
<!-- CSS styles -->
      /* Sample CSS styles here */
    

I apologize for any confusion caused by my usage of snippet system and the variable names mentioned in the code. Thank you for understanding.

Answer №1

A few adjustments were made to address the issue you are facing:

  1. Instead of using $(".encadrer"), I replaced it with $(moveDiv) to ensure that the plugin is not called for all elements (.encadrer) every time a user adds an image.
  2. The primary issue was with the positioning of the images, which was set to relative but I changed it to absolute.
  3. I eliminated the properties display:table-cell and vertical-align:middle. If you want to center the image, it's recommended to refer to this guide on How to center absolute element in div.

var bg = document.getElementById('bg');
bg.className = "centrer";

var ajoutImg = document.getElementById('ajoutImage');

var initDiagonal;
var initFontSize;

ajoutImg.onclick = function () {
  //var moveDiv = document.createElement("div");
  //moveDiv.className = 'encadrer';
  //var titre = document.createElement("p");
  //var para = document.createElement("p");
  //titre.textContent = "Titre";
  //titre.className = 'centrerTitre';
  //moveDiv.appendChild(titre);
  //para.className = 'centrerPara';
  //moveDiv.appendChild(para);

  var name = prompt("Texte de l'image :");
  var container = $('<div class="encadrer"><div class="inner"><p class="centrerTitre">Titre</p><p class="centrerPara">' + name + '</p></div></div>');

  $(bg).append(container);

    container
    .draggable({ containment: "parent" })
    .resizable({
      containment: "parent",
      handles: "all"
    });
};
.centrer {
   display: block;
   margin: auto;
   position: absolute;
   top: 0;
   bottom: 0;
   left: 0;
   right: 0;
   height: 640px;
   width: 360px;
   background-color: #000000;
 }

.menu {
  border: 1px solid black;
  padding-left: 15px;
  padding-right: 15px;
  padding-top: 2px;
  padding-bottom: 2px;
  float: left;
}

.encadrer {
  /*display: table-cell;
  vertical-align: middle;*/
  border: 1px solid white;
  position:absolute !important;
}

.centrerTitre {
  color: white;
  margin: auto;
  text-align: center;
  padding-top: 10px;
  padding-bottom: 10px;
  padding-left: 10px;
  padding-right: 10px;
} 

.centrerPara {
  font-size: 16;
  color: white;
  margin: auto;
  text-align: center;
  padding-top: 10px;
  padding-bottom: 10px;
  padding-left: 10px;
  padding-right: 10px;
}

.inner {
  display: inline-block;
  vertical-align: middle;
  text-align:center;
  width:100%;
}

.encadrer:before {
  content: "";
  display: inline-block;
  vertical-align: middle;
  height: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.css" rel="stylesheet" />

<div id="menu" class="menu">
    <h3>Ajouter des éléments</h3>
    <ul>
        <li><a id="ajoutImage" href="#" onclick="return false;">Image</a></li>
    </ul>
</div>
<div id="bg"></div>

Update

To center the content inside .encadrer, you should:

  1. Enclose the content within a div
  2. Refer to this tutorial: Vertically-> Is it inline or inline-* elements (like text or links)?-> Is it multiple lines? -> see the second demo. You can view the final outcome here

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

Creating an AJAX form using Jquery 3.3.1: A step-by-step guide

After updating my jQuery from version 1.10.2 to 3.3.1, I encountered a problem. Whenever I fill in the inputs and click the send button, my website simply reloads and the information from the inputs gets added to the URL of my website. The URL looks like t ...

Utilizing Express.js for reverse proxying a variety of web applications and their associated assets

I am looking to enable an authenticated client in Express to access other web applications running on the server but on different ports. For instance, I have express running on http://myDomain and another application running on port 9000. My goal is to re ...

Issues with PhoneGap file upload functionality

For my first time using phonegap, I am trying to upload a simple image to my server. Following the Full Example in the documentation (), I can open the image gallery and select the image, but nothing gets uploaded to the server, and the success or failure ...

The HTML division with text positioned at the top and bottom

For my project, I am looking to make a <div> with a height of 200px that contains text at both the top and bottom. My goal is for this design to be compatible with all popular web browsers. Despite experimenting with different combinations of align ...

Concealing the text input cursor (caret) from peeking through overlaid elements on Internet Explorer

Currently, I am facing an issue with a form that includes a unique widget. This particular widget automatically populates a text input when it is in focus. The problem arises when the widget appears above the text input as intended. In Internet Explorer ...

Can someone assist me in locating a specific web element using Selenium in Java?

Here is the original HTML code snippet: <input id="ember354" class="ember-view ember-text-field search" placeholder="Ask me anything!" type="text"> This element can be reached through body-div-div-input. Attempts to find the element by tag name f ...

Adding supplementary documents within the app.asar file via electron

This is a Vue application using electron-builder. { "scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build", "electron:build": "vue-cli-service electron:build", "electron:serve": "vue-cli-service electron:serve", ...

PHP/HTML- checkbox - Customize your website with interactive form

I am trying to pass checked ids from one page to another. Here is my code: <html> <body> <form action="del_novica_admin_sql.php" method="POST"> <table border="2"> <?php $st=0; include 'co ...

Challenges with transitioning to IE 11

During the process of moving our application from IE 8 to IE 11, we encountered an unexpected problem. The following jQuery code that functioned properly in IE8 is failing to work in IE11. $("#Submit").attr("disabled", "disabled"); Is there anyone who ca ...

ReactJs not responding to rotation feature

System: Operating System: Windows 7 - 64 bit I am attempting to manipulate the rotation of a div in Reactjs by using click and drag mouse events similar to this example written in javascript code, which works flawlessly. I created a ReactJs applicatio ...

Describe the ng-model for this specific JSON input array in AngularJS

Aim: The task at hand is to update the data in the following format: "open_hours": [ // (Note that open_hours is an array). { "weekday": "mon", "opens_at": "09:00", "closes_at": "22:00" }, { "weekday": "t ...

Bring Component into Vue if necessary

I have multiple menu types and would like to determine which type of menu to use by configuring it in .env.local. For example: VUE_APP_MENU_TYPE=2 Here is the code snippet from my javascript file: let menu = false; if (process.env.VUE_APP_MENU_TYPE === &q ...

The promise node design pattern

I'm dealing with a node issue where I need to call a Data Access Object and possibly others within it, and then render a Jade template once everything is done. Here's an example of what I want to achieve: provider1.getData(args, function(error ...

How to toggle elements using CSS slide animations?

Is there a way to make a div slide in and out from the left to right when the user clicks on "clickthis"? Here is an example of CSS code: .container{width:100px; position:absolute; left:-70px;} .container .open{left:0px;} .button{display:block; top:0px; ...

Sending a request for the second time may result in data duplication

To upload a file to the server, I use the following code snippet: var fd = new FormData(); fd.append('folder', 'html'); fd.append('permission', 0); fd.append("file", file, file.name); After selecting the file from an input f ...

External CSS File causing improper sizing of canvas image

I have been working on implementing the HTML5 canvas element. To draw an image into the canvas, I am using the following javascript code: var img = new Image(); var canvas = this.e; var ctx = canvas.getContext('2d'); img.src = options.imageSrc; ...

Utilizing JavaScript to eliminate objects from a collection and showcase a refreshed arrangement

On a simple webpage using bootstrap and js/jquery, data is fetched via ajax to create entries displayed to the viewer. The process involves: - making a request - parsing XML to create an array of objects with all the data - sorting by one property - cr ...

Using Typescript to pass the setState function as a parameter

Consider the scenario below: // external file export const specificFunction = setState => { setState({ value: "some new string" }) } // component's file import { specificFunction } from "pathToFile" interface TState { ...

Seeking assistance in creating custom tabs for integration with a jQuery tabs plugin

Attempting to navigate the world of CSS as a newbie, I find myself struggling with creating tabs. Our current tab setup can be viewed here, but unfortunately, these tabs are created using an unattractive <table> tag. Below is the code responsible fo ...

Setting up PhpStorm for Global NPM module resolution

I'm in the process of developing a WordPress plugin, and the directory path I'm focusing on is: wp-content/plugins/pg-assets-portfolio/package.json I currently have the NodeJS and JavaScript support plugins installed (Version: 171.4694.2 and V ...