How can I toggle sort order with a button on bootstrap page without reloading page?

181 views Asked by At

I am building a template for an existing app, and want to include a button to change the sort order of elements displayed on a web page. The page uses Bootstrap 5.3 for styling, so I already have jQuery and other features of Bootstrap available.

I simply want a button that reverses the order of the array allowing toggling the sort order, and reflects this on the page without reloading it.

Here is the HTML for some entries:

<button type="button" onClick="reverseEntries();">Reverse order of entries</button>
<div id="entries">
  <div class="card">
    <h2>Entry 0</h2>
  </div>
  <div class="card">
    <h2>Entry 1</h2>
  </div>
  <div class="card">
    <h2>Entry 2</h2>
  </div>
</div>

The elements I want to sort are available from a JavaScript object named entries that is already populated when the page loads. For simplicity sake, you can treat it as an array like this:

entries = [
   'Entry 0',
   'Entry 1',
   'Entry 2'
]

The template engine is dot.js, and iterates through the array and writes each div client side - i.e. each array member value is written between the h2 tags.

Here is the template, that builds the html snippet.

<div id="entries">
  {{~ entries:entry:index}} <!-- iterates through the entries array -->
  <div class="card">
    <h2>{{=entry}}</h2>
  </div>
  {{~}} <!-- end of iteration block -->
</div>

I can use entries.reverse() to reverse the order of the array, but I'm not sure how to redo the page after reversing the array.

Here is the function so far:

function reverseEntries(){
  entries = entries.reverse(); // this successfully reverses the array
  // how can I update the page so the entries appear in the new order of the array.
}

I could achieve the same output by just reloading the page with a different query, but since all the data is already in JavaScript I'd prefer to do it client side.

1

There are 1 answers

2
dunxd On

Thanks to some suggestions and probing questions in the comments, I figured out what I needed to do using jQuery to refresh the HTML in my template.

Key was understanding how doT.js writes the page.

After reversing the array, I needed to recompile the relevant template incorporating the data, then use jQuery to rewrite the HTML in the relevant container.

function reverseEntriesOrder() {
  var template = doT.template("entries.html"); // Loads the template text into doT
  var resultHTML = template(entries.reverse()); // applies the changed data to the template
  $('#main').html(resultHTML); // updates the HTML in the main DIV with the new value
}

Now I can call reverseEntriesOrder() from an onClick event and the order of the items will be updated.