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)
You can use global event hooks and data- tags to process and store parameters for internal (i.e. between #blah -> #blah2) transitions:
In your HTML you can go
< a href="#photo" data-params="id=123">....< /a>
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.
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With