Joemo Joemo - 2 months ago 8
HTML Question

Swapping div position depending on screen width

I'm trying to create a responsive website and would like two div's to swap position depending on the screen width (on start and when resizing).

I have done some research and tried a few options but had no luck. I'm fairly new to JQuery and JS so any help would be greatly appreciated.

html

<div id="div1">facebook</div>
<br/>
<div id="div2"><img src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcSFjZm7TgmvK8lEfSkzytyCuE1ZDE1WdexDyj7eRLSPHfexJQruR8uIGfY"/></div>


jquery

$(document).ready(function(){
div1 = $('#div1');
div2 = $('#div2');
tdiv1 = div1.clone();
tdiv2 = div2.clone();
.resize()
});

$(window).resize(function() { //Fires when window is resized
if($(window).width() < 800){
div1.replaceWith(tdiv2);
div2.replaceWith(tdiv1);}
else{
div1.replaceWith(tdiv1);
div2.replaceWith(tdiv2);}
});

Answer

The easiest way to achieve this is to put it in a wrapper and append() and prepend() the divs within the wrapper:

JS Fiddle

HTML

<div class="wrapper">
  <div id="div1">facebook</div>
  <br/>
  <div id="div2">
    <img src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcSFjZm7TgmvK8lEfSkzytyCuE1ZDE1WdexDyj7eRLSPHfexJQruR8uIGfY" />
  </div>
</div>

Jquery

$(window).on('load resize', function() { //Fires when window is loaded or resized
  var div1 = $('#div1');
  var div2 = $('#div2');
  var wrapper = $('.wrapper');

  if ($(window).width() < 800) {
    wrapper.prepend(div1).append(div2); // move div 1 to start & div2 to end
  } else {
    wrapper.prepend(div2).append(div1); // move div 2 to start & div 1 to end
  }
});

And in case you want to write it in a different way:

JS Fiddle

$(window).on('load resize', function() { //Fires when window is loaded or resized
  var windowWidth = $(window).width(),
      div1 = $('#div1'),
      div2 = $('#div2'),
      first = windowWidth < 800 ? div1 : div2,
      last = windowWidth >= 800 ? div2 : div1;

      $('.wrapper').prepend(first).append(last); 
});
Comments