Patryk Śliwiński
Patryk Śliwiński

Reputation: 21

jQuery clone clone element with style properties

I want to make draggable history. When draggable stop it should push whole DOM to let history = [] and then whenever someone click on button then last DOM should be brought back but it doesn't work. When I try to bring back previous DOM, it doesn't clone correctly. It looks like style="top: , left:" property isn't cloned. Anyone can help?

let history = [];

function pushHistory() {
  history.push($('.page').each(function() {
    return $(this).clone(true, true)
  }))
}

function backHistory() {
  history.pop();
  $(history[history.length - 1]).each(function() {
    $(this).detach().appendTo($('.outer'))
  })
}
$(".page").draggable({
  stop: function(event, ui) {
    pushHistory();
  }
})

$('button').on('click', function() {
  backHistory();
})
.page {
  display: inline-block;
  background-color: red;
  width: 50px;
  height: 50px;
  position: relative;
  color: white;
  font-size: 3em;
  text-align: center;
  line-height: 50px;
}

.back {
  position: absolute;
  top: 0px;
  right: 0px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div class="outer">
  <div class="page">
    1
  </div>
  <div class="page">
    2
  </div>
  <div class="page">
    3
  </div>
  <div class="page">
    4
  </div>
  <div class="page">
    5
  </div>
  <div class="page">
    6
  </div>
</div>
<button class="back">
Back
</button>

Upvotes: 2

Views: 174

Answers (1)

emanuelpoletto
emanuelpoletto

Reputation: 174

I've made a little adjustment on the JavaScript part as follows and it works:

let history = [];

function pushHistory(el) {
    history.push({
        index: el.index(),
        offset: el.offset()
    })
}

function backHistory() {
    let el = history[history.length - 1];
    if (el) {
        $('.outer').find('.page').eq(el.index).offset(el.offset);
        history.pop();
    }
}

$('.page').draggable({
    start: function() {
        pushHistory($(this))
    }
})

$('button').on('click', function() {
    backHistory();
})

Basically, it's now saving the index and offset of the element on draggable "start" event. Then, the backHistory acts just on the last dragged element.

It's running here: https://jsfiddle.net/12sdku0e/

Upvotes: 1

Related Questions