Joemo Joemo - 1 year ago 53
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.


<div id="div1">facebook</div>
<div id="div2"><img src=""/></div>


div1 = $('#div1');
div2 = $('#div2');
tdiv1 = div1.clone();
tdiv2 = div2.clone();

$(window).resize(function() { //Fires when window is resized
if($(window).width() < 800){

Answer Source

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

JS Fiddle


<div class="wrapper">
  <div id="div1">facebook</div>
  <div id="div2">
    <img src="" />


$(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;