Is it possible to rearrange the div’s so they are alphabetically in order - A,B,C,D
I haven’t attempted any code yet but is posible to add a reference to the div’s into an array and then order the array based on the letter in the div - that sounds crazy but i can’t think of any other way of doing this.
You don’t need to create so many arrays. You can just get a reference to all of the divs you want to sort, then use JavaScript’s native .sort() function.
var $divs = $("div.box");
$('#alphBnt').on('click', function(){
var alphabeticallyOrderedDivs = $divs.sort(function(a,b){
return $(a).find("h1").text() > $(b).find("h1").text();
});
$("#container").html(alphabeticallyOrderedDivs);
});
$('#numBnt').on('click', function(){
var numericallyOrderedDivs = $divs.sort(function(a,b){
return $(a).find("h2").text() > $(b).find("h2").text();
});
$("#container").html(numericallyOrderedDivs);
});
Sure.
You are passing sort() a callback.
This callback is called many times over for your array, where a is the current item and b is the next item.
The callback compares both items and returns 0 if the two elements are equal, a negative number if a should be before b and a positive number if b should be before a.
Based on the return value it orders the items in the array correspondingly.
I would also recommend that you hang around the JS forum and try to answer questions here.
It is really an excellent way to learn, as well as to cement your own knowledge.
Your solution seems to be exactly what I need, but i can’t seem to get it working!
On this site: http://www.webpol.dk/VisArtikel.asp?TemplateID=525&kat=5 (at first you’ll get redirected to the front page, but then just paste the url again), I’ve tried to adapt your code to our site, but it isn’t working. Would be look through the code and tell me why not? It’s the boxes containing our products, that need sorting!
The following jquery is on the site:
var $divs = $("div.vareboxtd");
$('#alphBnt').on('click', function () {
var alphabeticallyOrderedDivs = $divs.sort(function (a, b) {
return $(a).find(".varetekstiboks").text() > $(b).find(".varetekstiboks").text();
});
$(".midttable").append(alphabeticallyOrderedDivs);
});
$('#numBnt').on('click', function () {
var numericallyOrderedDivs = $divs.sort(function (a, b) {
return $(a).find(".varepointiboks").text() > $(b).find(".varepointiboks").text();
});
$(".midttable").append(numericallyOrderedDivs);
});
I had a look at your site.
The page you link to is 4410 lines long and contains inline CSS and inline JS.
This makes it a bit difficult to see what is happening where.
Would it be possible for you to make a simple test page which removes the unnecessary JS, with minimal styling and only five or so products?
That way it’ll be much easier to get to the root of your problem.
When you have done that, just post the link back here.