csshovermousehoveronhover

How to apply CSS on child element when hover parent element?


I'm working on pure javascript draggable and sizable div. Everything is okay, But I have just one problem which is when I hover on the parent div I need to show the handle which is just a children div.

You can semply remove and readd .onHover {display: none;} to see the targeted div. and you can find a related example in this link

HTML

<div id="DraggableImage">
  <div id="DraggableImageHandle" class="onHover">move</div>
</div>

CSS

    #DraggableImage {
      position: absolute;
      z-index: 9;
      background-color: #f1f1f1;
      text-align: center;
      border: 1px solid #d3d3d3;
      overflow: hidden;
      resize: both;
      width: 500px;
      height: 300px;
      
      background-image: url("https://media-exp3.licdn.com/dms/image/C560BAQHMG7ReC3Layw/company-logo_200_200/0/1519874455151?e=2159024400&v=beta&t=FYZf0Jr4bhHIaWgGlQ8wTYVU4phKbinvvvcnNGRVGHA");
      background-position: center;
      background-repeat: no-repeat;
      background-size: cover;
    }
    
    #DraggableImageHandle {
      padding: 10px;
      cursor: move;
      z-index: 10;
      background-color: blueviolet;
      color: #fff;
      position: absolute;
      top:calc(50% - 35px);
      left: calc(50% - 50px);
      height: 50px;
      width: 80px;
    }
    
    
    .onHover {
      display: none;
    }
    
    #DraggableImage:hover + .onHover{
      display: block;
    }

JavaScript

//Make the DIV element draggagle:
dragElement(document.getElementById("DraggableImage"));

function dragElement(elmnt) {
  var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  if (document.getElementById(elmnt.id + "Handle")) {
    /* if present, the header is where you move the DIV from:*/
    document.getElementById(elmnt.id + "Handle").onmousedown = 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;
  }
}

Solution

  • Remove the +

     #DraggableImage:hover .onHover{
          display: block;
        }