Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery mobile: supply parameters in hash URL?

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)

like image 703
simon Avatar asked Apr 26 '11 14:04

simon


2 Answers

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.

like image 114
Art Avatar answered Sep 28 '22 08:09

Art


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");
}
like image 39
Nick Avatar answered Sep 28 '22 07:09

Nick