Search code examples
jquery-mobilebackbrowser-history

Find my index.html (first) page in my jQueryMobile history


I am using single page AJAX loading of jQMobile. Each page is its own file.

I dynamically create a HOME button on my pages when I need to. Today I just use an <A> tag pointing back to "index.html". Is there any way I can check my web app jQueryMobile history to find the first time in history where my index.html page was loaded and call a window.history.back(-##); to the page instead of just adding to the history and navigation.

The code will be such that if there isn't a index.html in the history, I will just window.location.href to the page.

function
GoHome()
{

  /* This is a function I don't know even exists, but it would find the first occurrence of index.html */
  var togo = $mobile.urlHistory.find( 'index.html' )  
  var toback = $mobile.urlHistory.length -1 - togo;

  if ( togo >= 0 )
    window.history.back( -1 * toback )
  else
    $.mobile.changePage( '/index.html' )

}

If the history was index.html => profile.html => photos.html The magic function of $.mobile.urlHistory.find('index.html') would return 0, the history length would be 3, so my calculation would be to window.history.back( -2 ) to get back to the index.html page. if that find function returned -1 then it wasn't found and I would just do a changepage call.

Thanks /Andy


Solution

  • After reading and reading and reading and not really sure what I was reading anymore, I wrote this function. Not sure its correct or the best solution or even if it can be condensed down.

    using this to call

    console.log( 'FindHome: ' + FindHome( ["", 'index.html'] ) );
    

    It will search though from the first entry to the current index in the jQueryMobile urlHistory.stack and see if it will find an index page or not. From there I can decide what to do if I want to load a new page or go back -xx to the one already in history. This way the history will be somewhat clean.

    function
    FindHome( _home )
    {
    var stk = $.mobile.urlHistory.stack;
    var ai  = $.mobile.urlHistory.activeIndex;
    
    for ( var idx=0; idx <= ai; idx++ )
    {
        var obj = $.mobile.path.parseUrl( $.mobile.urlHistory.stack[idx].url );
        if(typeof _home == "string")
        {
            if ( _home == obj.filename )
                return( idx - ai );
        }
        else
        {
            for(var x in _home)
            {
                if ( _home[x] == obj.filename )
                    return( idx - ai );
            }               
        }
    }
    
    return ( 0 );   
    }