I'm creating a jQuery Mobile app with a glossary. Any time the user touches a term that is in the glossary I want it to open the glossary, open the collapsible with that id, and scroll to it.
// get all links within an element, assign click handler
var links = element.find(".glossaryLink");
links.each(function(index){
$(this).on("click", function(){
var regex = /\W/g;
var searchID = this.innerHTML.replace(regex, "").toLowerCase();
// open the glossary
window.location = "#glossary";
var entry = $("#" + searchID);
// This is working fine, the correct collapsible is opening
entry.collapsible( "option", "collapsed", false );
// But this always returns 0...
var pos = entry.offset().top;
// ...meaning this does nothing
$.mobile.silentScroll(pos);
}
});
The code seems to be working OK in that I can open the correct collapsible (I'm getting the correct <div>
within the collapsible-set) but its value of pos
is always 0, so it doesn't scroll.
The jQuery API for offset() says that it doesn't support hidden elements but this post seems to suggest that auto-scrolling is possible on a collapsible.
Any help much appreciated!
EDIT
As I've said in the comments below, the setTimeout() trick isn't working if the time < 500ms. Using @Omar ingenious solution of assigning a listener then immediately kicking it off works...
function addGlossaryClickHandlers(element){
var links = element.find(".glossaryLink");
links.each(function(index){
$(this).on("click", function(){
var regex = /\W/g;
var searchID = this.innerHTML.replace(regex, "").toLowerCase();
window.location = "#glossary";
var entry = $("#" + searchID);
// assign listener then kick it off by expanding the collapsible
entry.on("collapsibleexpand", function(){
var pos = entry.offset().top;
$.mobile.silentScroll(pos);
}).collapsible("expand");
});
});
}
...but pos
above is again returning 0. Stumped again, can anyone help? Stripped down JSFiddle although for some reason the last link in the collapsible is broken...