changing order of flex boxes.

In this example below you will see how to do a changing order of flex boxes. with some HTML / CSS and Javascript

Nothing fancy here. When you click a box, it is moved to the front of the stack. Most recently clicked boxes at the front - so as you click other boxes, they will move back in the order they were clicked.

Thumbnail
This awesome code was written by aaronjamesyoung, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright aaronjamesyoung ©

Technologies

  • HTML
  • CSS
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>changing order of flex boxes.</title>
  
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">

  
      <link rel="stylesheet" href="css/style.css">

  
</head>

<body>

  <div class="wrap">
	<div>FIRST</div>
	<div>SECOND</div>
	<div>THIRD</div>
	<div>FOURTH</div>
	<div>FIFTH</div>
</div>
  <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>

  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/aaronjamesyoung/changing-order-of-flex-boxes-aBDCu */
.wrap {
  height: 100px;
  background: gray;
  display: flex;
  justify-content: space-between;
}

.wrap div {
  width: 100%;
  order: 1000;
  opacity: 0.3;
  transition: opacity 0.15s ease-in;
}

.wrap div.first {
  opacity: 1;
}

.wrap div:hover {
  opacity: 0.8;
}

.wrap div:nth-of-type(1) {
  background: red;
}

.wrap div:nth-of-type(2) {
  background: green;
}

.wrap div:nth-of-type(3) {
  background: yellow;
}

.wrap div:nth-of-type(4) {
  background: blue;
}

.wrap div:nth-of-type(5) {
  background: orange;
}


/*Downloaded from https://www.codeseek.co/aaronjamesyoung/changing-order-of-flex-boxes-aBDCu */
// Set a "first" tab
$(document).ready(function() {
  $('.wrap div:first-of-type').addClass('first').css('order', 1);
});

// On clicking another tab:
// 1. All inactive tabs with class "incrementer" get pushed down
// 2. The previously active tab gets "first" class removed and has its order incremented, and gets class "incrementer" so that it continues to get incremented later
// 3. Current tab gets "incrementer" class removed, "first" class added, and is moved to the front of the stack.
$('.wrap div').click(function() {
  $('.incrementer').css('order', '+=1');
  $('.first').css('order', '+=1').removeClass('first').addClass('incrementer');
  $(this).removeClass('incrementer').addClass('first').css('order', 1);
});

Comments