1

Is it possible with jquery to trigger a function when the user clicks the browsers back button. I have a lightbox/widget that when open fills the window when it is open. There is a close button etc but this would be good if this closed if a user hit the back button by mistake.

I have this so far but the function doesnt seem to run at all

$(window).on("navigate", function (event, data) {
            event.preventDefault();
            console.log('BACK PRESSED');
            var direction = data.state.direction;
            if (direction === 'back') {
                if(widgets.full_active){
                    $('.close', widgets.active_widget).click();
                    event.preventDefault();
                    console.log('CLOSE THIS');
                }
            }
            if (direction === 'forward') {
                // do something else
            }
        });

By not running this line at the start of the function event.preventDefault(); should mean the page never changes

Paul Ledger
  • 1,125
  • 4
  • 21
  • 46

1 Answers1

0

Usually, I do this using the native JavaScript API from the browser, like described here: Manipulating the Broser History.

With jQuery, I see people usually using this plugin: History.js, although I have no idea what is it's status.

The event you're looking for is onpopstate.

A popstate event is dispatched to the window every time the active history entry changes between two history entries for the same document.

Matheus Dal'Pizzol
  • 5,735
  • 3
  • 19
  • 29