Resizing one element using jQuery UI changing the position of another

1.3k views Asked by At

I am trying to make resizible and draggable lines out of labels using jQuery UI.

The problem is, if I add two labels and try to resize the first label, it changes the position of the second label (but if I resize the second label it does not change the position of the first label).

How to prevent labels from changing other label's position while resizing..?

HTML:

<div id="main">
  <button id="s">add line</button>
</div>
<div id="line" class="hidden">
  <label class="dra"></label>
</div>

JS:

function makeline() {

  $t = $(".dra", "#line").clone(true).draggable().resizable({
    handles: "s, n"
  });

$("#main").append($t);
}
$("#s").click(function () {
  makeline();
});

CSS:

.dra {
  display: block;
  background-color:red;
  width: 7px;
  height: 80px;
  border: 1px solid red;
}
.hidden {
  display: none;
}
#main {
  border: 1px solid black;
  width:500px;
  height: 300px;
}

UPDATE: Full code in JSFiddle

2

There are 2 answers

0
T J On BEST ANSWER

This is happening because the jQuery UI widgets set the position of element to relative by default, leaving it in the normal flow of the document. You can work around this issue by applying position:absolute for the elements like:

.ui-resizable {
  position:absolute !important;
}

This will cause them to stack on top of each other rather than one below another since they aren't in the normal flow anymore. You can easily fix this using the jQuery ui position() utility method as shown below:

$("#s").click(function() {
  $t = $("#line .dra").clone(true).draggable().resizable({
    handles: "s, n"
  })
  if ($("#main").find(".dra").length) {
    $t.position({
      at: "left bottom",
      of: "#main .dra:last"
    })
  };
  $("#main").append($t);
});
.dra {
  display: block;
  background-color: red;
  width: 7px;
  height: 80px;
  border: 1px solid red;
}
.hidden {
  display: none;
}
#main {
  border: 1px solid black;
  width: 500px;
  height: 300px;
}
.ui-resizable {
  position: absolute !important;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<div class="form-group">
  <label>ADD two line and RESIZE THE FIRST LINE it will scroll down the line added after it. NOW add a 3rd line and resize the second line it will scroll down the 3rd line and if you resize the very first line you added it will scroll down the other lines</label>
  <div id="main">
    <button id="s">add line</button>
  </div>
  <div id="line" class="hidden">
    <label class="dra"></label>
  </div>

You can adjust the positioning however you want.

0
kmandov On

If your label is:

<div class="label">Lorem ipsum</div>

add this CSS:

.label {
    white-space: nowrap;
}