Reputation: 2559
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!
Upvotes: 0
Views: 25
Reputation: 84
Inside the function you were statically assigning the divs to your arguments, and your variables were private because they were inside the function and that's why you couldn't access them inside your if statement. Instead do this:
// global variables
var divOrder,
url = document.location.href,
divOne = $('.div-1'),
divTwo = $('.div-2'),
divThree = $('.div-3'),
divFour = $('.div-4');
divOrder = function (div1, div2, div3, div4) {
$('#container').empty().append(div1, div2, div3, div4);
};
// tested it directly
divOrder(divThree, divTwo, divFour, 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);
}
Upvotes: 1
Reputation: 10782
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>
Upvotes: 1