Search code examples
javascriptjqueryback-buttonhashchange

Jquery History / Hashchange Event - Back button - On form submit


So i am using the Ben Alman history plug in to manage the back button functionality in my js/ajax application:

Read about the plugin here: JQuery Hashchange

It works fine on all of my links 'a' that contain an href but it doesn't not create a hash when an input button is clicked. How do I add this functionality? I have a lot of ajax forms that are process using buttons and need to make sure a hash is created on that event as well. Thank you for all your help.


Solution

  • From the documentation

    // Manually trigger the event handler.
    jQuery(window).hashchange();
    

    So you will need to have something like

    $('input#mybutton').click(function(){
        $(window).hashchange()
    
        // or directly changing the hash will trigger it too
    
        location.hash = 'somehash';        
    }
    

    Most history plugins I've looked at just work on a timer, so every 50 or so milliseconds they check to see whether the hash is the same as what it was before. If it's not, they fire that event. So when you change location.hash directly, it will recognise it and fire the event. Or so the theory goes...