Search code examples
javascriptjqueryeventsdom-eventstarget

Change position through DOM EVENT FLOW - Jquery/JS


I want to change the <div> position after the user stops dragging it. Also the number 10 without commas doesn't work.

It does change to a blue color, but the position doesn't. What can I do? I have a lot of .screen divs. Thanks!

$('.screen').draggable({
  stop: function(event, ui) {
    if (parseInt(event.target.offsetTop) < -1) {
      event.target.style.backgroundColor = "blue";
      event.target.style.offsetTop = "10";
    }
  }
})

Solution

  • There's two main issues here. Firstly offsetTop is a property of the Element object, not the style of the Element.

    Secondly offsetTop is readonly, so you cannot use it to update the position of the element. To do that you need to set style.top:

    $('.screen').draggable({
      stop: function(event, ui) {
        if (event.target.offsetTop < -1) {
          event.target.style.backgroundColor = "blue";
          event.target.style.top = '10px';
        }
      }
    })
    <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.min.js"></script>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
    <div class="screen">Drag me</div>

    Also note that offsetTop returns an integer value, so parseInt() is not required.