How can i prevent my draggable menu go outside a div in Polymer 2?

57 Views Asked by At

I have a draggable menu that i want it to be restricted within parent in Polymer 2

enter image description here this is the issue

Here is my draggable function, i saw that there is a way to fix my problem using javascript vanilla but i tried with polymer and it doesnt work

    dragElement: function(elmnt) {
  var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  if (Polymer.dom(this.root).querySelector("#" + elmnt.id + "header")) {
    // if present, the header is where you move the DIV from:
       Polymer.dom(this.root).querySelector("#" + elmnt.id + "header").addEventListener("mousedown", dragMouseDown);
  } else {
    // otherwise, move the DIV from anywhere inside the DIV:
    elmnt.onmousedown = dragMouseDown;
  }


  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    // get the mouse cursor position at startup:
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    // call a function whenever the cursor moves:
    document.onmousemove = elementDrag;
  }

  function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();
    // calculate the new cursor position:
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    // set the element's new position:
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  }

  function closeDragElement() {
    // stop moving when mouse button is released:
    document.onmouseup = null;
    document.onmousemove = null;
  }  
}

Here is the HTML of the menu

<menu id="controls">
    <div id="mydiv" style="display: flex; align-items: center;">
        <div id="mydivheader" style=" margin-right: 5px;"> 
            <iron-icon class="show-button special-button arrow-img"  icon="image:adjust" style="color:[[eyeColor]];"></iron-icon>
        </div>
        <div class="operations-3d" id="mydivheader" style="opacity: 1;">
            <paper-button on-click="hideShowOptions" id="arrow-operation" toggles > 
                <iron-icon class="show-button arrow-img"  icon="icons:chevron-right" style="color:[[eyeColor]];"></iron-icon>
            </paper-button>
            <div class="operations">
                <paper-button onclick="test1click()" toggles > 
                    <iron-icon class="show-button"  icon="social:public" style="color:[[eyeColor]];"></iron-icon>
                </paper-button>
                <paper-button id="show" on-click="setOpacityTo">  
                    <iron-icon class="show-button"  icon="image:remove-red-eye"></iron-icon>
                </paper-button>
            </div>
        </div>              
    </div>
</menu>
0

There are 0 best solutions below