Search code examples
javascripthtmlcssdrag-and-dropdraggable

Change border color of element when other element is dropped


I'm having problems changing the border of a div element once I drag and drop another element into it.

Here is a jsfiddle https://jsfiddle.net/0w2xagxc/

I've tried this, but if I implement that it stops making the element dropable.

var drop1 = document.getElementById('drop1');
drop1.ondrop = function(){
        if (event.target.id == 'tier-one'){
              drop1.style.border = 'border: 2px solid red;';
        }
        }

I'd appreciate any help. Thanks!


Solution

  • Just change the border style inside the drop function:

    function allowDrop(ev) {
      ev.preventDefault();
    }
    
    function drag(ev) {
      ev.dataTransfer.setData("text", ev.target.id);
    }
    
    function drop(ev) {
      ev.preventDefault();
      var data = ev.dataTransfer.getData("text");
      ev.target.appendChild(document.getElementById(data));
      ev.target.style.border = '2px solid red';
    }
    @import url('https://fonts.googleapis.com/css?family=Lato');
    .activity-wrap {
      background-image: url("https://champlain.instructure.com/files/53385420/download?verifier=84S6CTzvskHjpREc4V3tcLUVhStOZwrbsoj5rVaT&wrap=1");
      display: block;
      width: 803px;
      height: 463px;
      padding: 20px;
    }
    
    .test-activity-text {
      font-size: 1.5em;
      color: #5AAA5A;
      font-weight: bold;
      display: inline-block;
      position: relative;
      margin: auto;
      font-family: 'Lato';
      z-index: 2;
      padding: 20px;
      overflow: hidden;
    }
    
    .test-activity-text:hover {
      cursor: pointer;
      color: #4554A4;
    }
    
    .drop {
      display: inline-block;
      position: relative;
      width: 280px;
      height: 105px;
      border: 2px solid #aaaaaa;
      background-color: darkseagreen;
      overflow: hidden;
    }
    <div class="drop" id="drop1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
    <div class="test-activity-text" id="tier-one" draggable="true" ondragstart="drag(event)">Text for Testing</div>