Nick Nick - 3 months ago 12
jQuery Question

jQuery - Re-Order Divs Passing Order Through Function

I think (hope) this is a simple one. I don't fully understand what I'm doing here, so any help would be great!

I have 4 divs inside a container. I want to run a function

divOrder()
and pass through the order I want my divs displayed in, like so:
divOrder(divfour, divTwo, divThree, divOne);
this doesn't work and I'm not sure what the best way to go would be.

HTML:

<div id="container">
<div class="div-1">1</div>
<div class="div-2">2</div>
<div class="div-3">3</div>
<div class="div-4">4</div>
</div>


JS:

var divOrder,
url = document.location.href;

divOrder = function (divOne, divTwo, divThree, divFour) {
var divOne = $('.div-1'),
divTwo = $('.div-2'),
divThree = $('.div-3'),
divFour = $('.div-4');

$('#container').empty().append(divfour, divTwo, divThree, divOne);

}


if (url.indexOf('?test-1') > -1) {
divOrder(divfour, divTwo, divThree, divOne);
} else if (url.indexOf('?test-2') > -1) {
divOrder(divThree, divTwo, divFour, divOne);
} else if (url.indexOf('?test-3') > -1) {
divOrder(divOne, divTwo, divfour, divThree);
}


Fiddle: https://jsfiddle.net/Lvmoyw2u/

Thanks for your help!

Answer

Move your variable declaration above/below the function declaration.

I also recommend to use different names for the function's parameters, so you don't confuse them with the global variables.

var divOrder = function(d1, d2, d3, d4) {
  $('#container').empty().append(d1, d2, d3, d4);
}

var divOne = $('.div-1'),
  divTwo = $('.div-2'),
  divThree = $('.div-3'),
  divFour = $('.div-4');


setInterval(function() {
  divOrder(divOne, divTwo, divThree, divFour);
  setTimeout(function() {
    divOrder(divFour, divTwo, divThree, divOne);
    setTimeout(function() {
      // or without variables:
      divOrder($('.div-3'), $('.div-1'), $('.div-4'), $('.div-2'));
    }, 1000);
  }, 1000);
}, 3000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="container">
  <div class="div-1">1</div>
  <div class="div-2">2</div>
  <div class="div-3">3</div>
  <div class="div-4">4</div>
</div>