jQuery mobile: supply parameters in hash URL?

16,075

Solution 1

You can use global event hooks and data- tags to process and store parameters for internal (i.e. between #blah -> #blah2) transitions:

  1. In your HTML you can go

    < a href="#photo" data-params="id=123">....< /a>

  2. Intercept the clicks on all links and look for a specific data- element, say, data-params:

    $('a').live('click',
        function(e) {
            params = $(e.target).jqmData("params")
        }
    )
    

In this case you are creating a global params object, which you should be able to access in a uniform manner from all your code.

Solution 2

If you can structure your hashes like #photo?id=123, something like this can work:

$("#page").live("pageinit", function(e) {
    var id = $(e.target).attr("data-url").replace(/.*id=/, "");
    //now you have the id, do page-rendering logic
});

And to catch direct-links:

if (window.location.hash && window.location.hash.indexOf("?") !== -1) {
    var pageID = window.location.hash.split("?")[0];
    $(pageID).trigger("pageinit");
}
Share:
16,075
simon
Author by

simon

Updated on June 21, 2022

Comments

  • simon
    simon almost 2 years

    I'm working in jQuery mobile, which is great. I have a question about supplying parameters inside the hash part of a URL.

    Here's some example code. In the content part of the home page, I'd like to be able to link to a page called e.g. '#photo-123' and have it load the 'photo' page below. I'd then extract the photo number from the URL, and load image 123.

      <!-- Home page -->
        <div data-role="page" id="home"> 
            <div data-role="header">
                <h1>Home</h1> 
            </div> 
            <div data-role="content">    
                <p><a href="#photo" data-role="button">Photo ###</a></p>  
            </div> 
        </div> 
        <!-- Photo page -->
        <div data-role="page" id="photo">
            <div data-role="header">
                <h1>Photo ###</h1>
            </div>
            <div data-role="content">
                  <img id="myphoto" src="" />
            </div>
        </div>
    

    This is so I can reuse the URL, i.e. the user can reload that page directly.

    Is it possible to pass parameters inside a hash URL with jQuery mobile? (or indeed with HTML generally - I know it's possible with e.g. the BBQ plugin, but I'd rather avoid plugins if possible)

  • simon
    simon about 13 years
    so, using GET parameters is the only way? nothing clever I can do with hashes?
  • mcgrailm
    mcgrailm about 13 years
    not that I know of yet there may be new stuff once an rc i out.. you might want to see if others chime in here tough its still pretty new to me
  • Richard
    Richard over 12 years
    Thanks. Afraid this doesn't work for me because I want to be able to bookmark the link, so I need parameters in the URL.