Avinash Roy
Avinash Roy

Reputation: 25

Back button Event Listener

I have a Single page application. In that at the first instance I am displaying the Input page and the Output Div is hidden at that point of time.Later on when the Input data are submitted I hide the Input data and Use ajax call to calculated the the output and display the output result in the Output div. So basically the same page is present both for input and output page. Now I have a back button, when users click on that the Input div is shown and Output div is hidden.

$("#renderOutput").on("click", "#chngeIcon", function () {
    $('#renderOutput').hide();
    $('#InputPage').show();
});

Since it is a single page application if user click on the browser back button, than it is taken to previous visited site. I want to make back button to behave similar to my back button. Please help me.enter image description here

Upvotes: 1

Views: 4343

Answers (1)

Njuguna Mureithi
Njuguna Mureithi

Reputation: 3856

You can try popstate event handler, e.g:

window.addEventListener('popstate', function(event) {
    // The popstate event is fired each time when the current history entry changes.



    if ($("#InputPage").is(":visible") == false) {
        // Call Back button programmatically 
        history.back();
        // Uncomment below line to redirect to the previous page instead.
        // window.location = document.referrer
    } else {
        // Stay on the current page.
        history.pushState(null, null, window.location.pathname);
        $('#renderOutput').show();
        $('#InputPage').hide();
    }

    history.pushState(null, null, window.location.pathname);

}, false);

Hope that helps

Upvotes: 4

Related Questions