Lefka Lefka - 6 months ago 18
Javascript Question

How to change order of elements based on browser size?

I have three buttons that are stacked horizontally. Each button, when clicked, shows a div element. When the browser is resized to a mobile view, I want the elements to stack vertically. This occurs by default, but I would like to stack the div element directly underneath the button it is associated with.

This is what I want to display (desktop left, mobile right):

Correct desktop view
enter image description here

This is what I get (desktop left, mobile right):

Correct desktop view
Incorrect mobile view

Here's the basic HTML. If I move the associated divs directly underneath the buttons, it looks fine on mobile but incorrect on desktop.

<button onclick="updateValue(1)">Button 1</button>
<button onclick="updateValue(2)">Button 2</button>
<button onclick="updateValue(3)">Button 3</button>
<div id="div-1"><span>This is div 1!</span></div>
<div id="div-2"><span>This is div 2!</span></div>
<div id="div-3"><span>This is div 3!</span></div>


I did try to use floats on the buttons but I couldn't get the desired output. Here is a fiddle showing what I have right now.

JSFIDDLE

So how do I order the elements button + button + button > div on desktop, and button > div > button > button on mobile?

Answer

@Lefka here is an example using flexbox model.
When you resize the example in full page view to window less than 420px the elements will be reordered the way you expected.
Hope it help you to figure out your needs.

function updateValue(newValue) {
  for (i = 1; i <= 3; i++) { 
    var element = document.getElementById("div-" + i);
    element.className = "";
    if (newValue === i) {
      element.className = "show";
    }
  }
}
div {
  display: none;
}

.show {
  display: block;
}

.flex-parent {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-content: stretch;
  align-items: flex-start;
}

button {
  flex: 0 0 auto;
}

[id^="div-"] {
  flex: 1 1 100%;
}

@media screen and (max-width: 420px) {
  .flex-parent {
    display: flex;
    flex-direction: column;
    flex-wrap: nowrap;
    justify-content: flex-start;
    align-content: stretch;
    align-items: flex-start;
  }
  
  .button-1 {
    order: 0;
  }
  
  .button-2 {
    order: 2;
  }
  
  .button-3 {
    order: 4;
  }
  
  #div-1 {
    order: 1;
  }
  
  #div-2 {
    order: 3;
  }
  
  #div-3 {
    order: 5;
  }
} 
<div class="flex-parent">
  <button class="button-1" onclick="updateValue(1)">Button 1</button>
  <button class="button-2" onclick="updateValue(2)">Button 2</button>
  <button class="button-3" onclick="updateValue(3)">Button 3</button>
  <div id="div-1"><span>This is div 1!</span></div>
  <div id="div-2"><span>This is div 2!</span></div>
  <div id="div-3"><span>This is div 3!</span></div>
</div>

Comments