Hector Landete Hector Landete - 3 months ago 22
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

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
    
    event.preventDefault();
  }
});

More info :
https://developer.mozilla.org/en-US/docs/Web/API/History_API
https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate