Hector Landete Hector Landete - 1 year ago 289
jQuery Question

On back button trigger event

I'm doing a web site with tons of rows and when you press in a row I hidde the rest of them. To show again all of them you have to press again but the customer may want to press the back button of the browser/mobile.

I'm looking for a way in js or jquery that:

if rows are hidden and press back button do something (show again all rows), if not do normal back button funcionality.

Any idea?

Thanks in advance.

Answer Source

You need to use the history API.

Use history.pushState() to create a new state when clicking a row.

Register a callback to window.onpopstate to modify the behavior when the user click the back button (you can cancel the event and do your stuff).

Example (untested, jquery optional) :

$('.row').on('click', function() {
  // do your stuff
  window.pushState({rowId: rowId}); // you might need the additional parameters, particularly to change the URL

$(window).on('popstate', function(event) {
  if ('rowId' in event.state) {
    // do your stuff

More info :

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download