Reputation: 1465
I'm dynamically creating some buttons in jQM, like this:
return '<a href="#glossary" id="' + match + '" class="glossaryLink" data-transition="slide">' + match + '</a>';
This works fine for creating the buttons - they have the same id
as the text on the button and they link fine to the glossary page.
What I need to do is link to the specific place in the glossary page.
Now normally you'd do
<a href="glossary.html#' +match+ '">
But in jQM I'd have to do
<a href="#glossary#' + match + '">
and this doesn't seem to work. I creates an href
with #glossary#target
which doesn't work.
Is there any way to do this?
Upvotes: 0
Views: 264
Reputation: 31732
Easy solution, is to add a custom attribute to Anchor, e.g. data-subpage="#sectionOne"
, and store that value in a variable to retrieve value later when you change to glossary
page.
<a href="#glossary" data-subpage="#sectionTwo" class="ui-btn subpage">Section two</a>
In #glossary
page, add id
attribute to sectioin div matching data-subpage
in link but without hash #
.
<div data-role="page" id="glossary">
<div id="sectionOne">
<p>Section one</p>
</div>
</div>
Bind click event on Anchors with class subPage
using pagecreate
. Once clicked, store data-subpage
value in a global variable.
var subPage;
$(document).on("pagecreate", "#pageID", function () {
$(".subpage").on("click", function () {
subPage = $(this).data("subpage");
});
});
Once you have the value of subpage stored, you need to listen to pagecontainershow
in order to scroll to a div with id
stored in subPage variable.
You need first to defined whether the active page is glossary
or not using getActivePage
. Also, check that subPage
variable is neither null
nor undefined
. Otherwise, the page will open normally.
If active page is glossary
and subPage
is defined, retrieve .offset().top
of that div and the scroll to it either with animation or without animation.
Moreover, note that you need to setTimeout
to run scroll function to make sure that page is fully loaded and transition is done.
$(document).on("pagecontainershow", function () {
var activePage = $.mobile.pageContainer.pagecontainer("getActivePage")[0].id;
if ( !! subPage && activePage == "glossary") {
var scrollTo = $(subPage).offset().top;
setTimeout(function () {
/* $.mobile.silentScroll(scrollTo); without animation */
$("body").animate({
scrollTop: scrollTo
}, 500, function () { /* 500ms animation speed - it's up to you */
subPage = null; /* reset variable */
});
}, 300); /* scroll after 300ms - it's up to you */
}
});
Demo (1)
(1) Tested on iPhone 5 - Safari Mobile
Upvotes: 2