I have the following:
HTML:
<ul id="listing"></ul>
JS:
// sort functions:
function SortLen(arr, ascYN) {
arr.sort(function (a, b) {
if (ascYN) return a.length - b.length;
else return b.length - a.length;
});
}
function SortAZ (arr) {
arr.sort(function (a, b) {
if (a < b) return -1;
else if (a > b) return 1;
return 0;
});
}
function SortZA (arr) {
arr.sort(function (a, b) {
if (a > b) return -1;
else if (a < b) return 1;
return 0;
});
}
// define array
var listing = document.getElementById("listing");
var myStringArray = ["Saab", "Volvo", "BMW", "Mercedes", "Volkswagon", "Ford"];
// sort the array
// SortLen( myStringArray, false );
// SortLen( myStringArray, true );
// SortAZ( myStringArray );
SortZA( myStringArray );
// display the array
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
listing.innerHTML += "<li>" + myStringArray[i] + "</li>";
}
As the code stands at the moment, I have to comment out out of the sort options to change the sort output e.g.
SortLen( myStringArray, false );
// SortLen( myStringArray, true );
// SortAZ( myStringArray );
// SortZA( myStringArray );
And then I have to reload the page to pick up the change and sort the array differently.
I wondered if there could be any way I could change the code so that I can add links to the HTML to add links - e.g.
<div id="sort">
<a href="#" onclick="SortLen( myStringArray, false );">Long - Short</a>
<a href="#" onclick="SortLen( myStringArray, true );">Short-Long</a>
<a href="#" onclick="SortAZ( myStringArray );">Short-Long</a>
<a href="#" onclick="SortZA( myStringArray );">Long-Short</a>
</div>
So that when clicked, the LI items generated would be resorted dynamically without refreshing the page each time.
<button type="button" onclick="...">...<button>would be more semantically and functionally appropriate for triggering arbitrary JavaScript.console.log(myStringArray);to each sort function, and then click the sort link, the array is sorted correctly, but then the output of the page is not refreshed to reflect the re-sorted array...