Search code examples
htmljquerycssjquery-animateoverlap

How do I overlap elements containing shapes


What I want is for the two squares at each side to come together and become one i.e. one overlapping the other in the center of the wrapper. The problem I am having is that once they come together, one of the square drops down a level. Im not sure if this is achieved using jQuery or using CSS.

Please see my program here

$(document).ready(() => {
  $(".square").animate({
    backgroundColor: "red",
  }, 3000);

  $("#squareOne").animate({
    marginLeft: "+=45%",
  }, 800);

  $("#squareTwo").animate({
    marginRight: "+=45%",
  }, 800);
});
#wrapper {
  width: ...;
  margin: 100px auto;
  border: 1px solid black;
}

.square {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  display: inline-flex;
  justify-content: center;
  align-items: center;
  margin: 10% 30px;
}

#squareTwo {
  position: relative;
  float: right;
}

#squareOne {
  position: relative;
  background: #fff;
}


}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
  <div id="wrapper">
    <div class="square" id="squareOne"></div>
    <div class="square" id="squareTwo"></div>
  </div>
</body>


Solution

  • If you want the squares to overlap, they have to be absolutely positionned.

    Then, there is a calculation about the distance to be travelled...

    $(document).ready(() => {
      $(".square").animate({backgroundColor: "red"},3000);
      
      // Calculate the slide distance
      // That is half the wrapper width minus the half of the square width
      let distanceToTravel = $("#wrapper").width() / 2 - $(".square").outerWidth() / 2;
    
      $("#squareOne").animate({marginLeft: distanceToTravel},800);
      $("#squareTwo").animate({marginRight: distanceToTravel},800);
    });
    #wrapper {
      margin: 100px auto;
      border: 1px solid black;
      position: relative;
      display: flex;
      justify-content: space-between;
      
    }
    .square {
      width: 100px;
      height: 100px;
      border: 1px solid black;
      margin: 10% 30px;
      position: absolute;
    }
    
    #squareTwo {
      right: 0;
    }
    <head>
      <meta charset="utf-8">
      <title>JavaScript</title>
      <link rel="stylesheet" href="styles/styles.css">
      <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
      <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
      <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
      <script src="scripts/fma_t5.js"></script>
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    
    <body>
      <div id="wrapper">
        <div class="square" id="squareOne"></div>
        <div class="square" id="squareTwo"></div>
      </div>
    </body>