Reputation: 456
In the following exampmle I'm setting an array of objects and sort them by a key parameter (position). I then need to output the result - but how? See the comment in the code.
$(document).ready(function () {
function sortHooks(){
// add modules
var modules = [
{ module: 'navbar', hook: 'hook-header', position: '2'},
{ module: 'logo', hook: 'hook-header', position: '3'},
{ module: 'description', hook: 'hook-header', position: '1'}
];
// sort by "position" ASC
function byPosition(a,b) {
if (a.position < b.position)
return -1;
if (a.position > b.position)
return 1;
return 0;
}
// jQuery function with the given parameters
/* for each modules as modules
for each hook as hook
do the following:
$( '#' + module )prependTo( '#' + hook )
so for the given example it should return
$('#description')prependTo('hook-header')
$('#navbar')prependTo('hook-header')
$('#logo')prependTo('hook-header')
so they can be executed in that specific order.
And since we're using "prepend" that will mean
that the items be placed like this:
#logo
#navbar
#description
*/
return ???
}
// Execute sortHooks function
sortHooks();
});
Maybe something like this, but I'm not exactly sure:
$.each(modules, function(index, value) {
$( '#' + value.module ).prependTo( '#' + value.hook ));
});
I've tried a bunch of other things as well, one of them being Hook elements with insertAfter, but stay in parent - jQuery , which worked perfectly, but if the position was higher than the children inside the parent it didn't know what to do with it and causing a lot of unwanted behavior.
Upvotes: 0
Views: 77
Reputation: 42736
just use a regular loop
for(var i=0; i<modules.length; i++){
$( '#' + modules[i].module )prependTo( '#' + modules[i].hook );
}
Upvotes: 1
Reputation: 288220
function byPosition(a,b) { return a.position-b.position; }
modules.sort(byPosition);
modules.forEach(function(obj){
$('#'+obj.madule).prependTo('#'+obj.hook);
});
Upvotes: 1