antanas_sepikas
antanas_sepikas

Reputation: 5704

jQuery mobile initialize all elements

I have elements on different jquery mobile pages, I use scripts that dynamically modify those elements values, the problem is those scripts are automated and I get exception e.g.:

Uncaught Error: cannot call methods on slider prior to initialization; 
attempted to call method 'refresh'

when I use something like this:

$('#tsetpoint').val(value).slider('refresh');

I think this happens because '#tsetpoint' element is being modified when the page it is on is not showed, to explain scenario: lets say I have 2 pages, "main" and "not-main". '#tsetpoint' element resides inside "not-main" page.

If I load my app with "not-main" page as default "myapp.html#not-main", the '#tsetpoint' element get's initialized and everything work's fine.

But if I start up with "myapp.html#main", there's no element '#tsetpoint' initialized and so I get the error.

So the question is how to initialize all elements on all pages, of jquery mobile, or how to check whether the element was initialized?

Upvotes: 2

Views: 1429

Answers (1)

Gajotres
Gajotres

Reputation: 57309

First you can't initialize all elements on all pages, that's not how jQuery Mobile works, it will severely slow down app initialization. Pages are initialized before they are shown.

Also you don't need to check if element is initialized plus no such function exist.

What you need to do is learn jQuery Mobile page events and how to trigger slider refresh only when appropriate page is about to be shown. You will need to use page events so you can trigger something only during some specific page initialization.

For example, this code will work up to jQuery Mobile 1.4.X versions:

$(document).on('pagebeforeshow', '#not-main', function(){ 
    //put your code here       
});

Or this code which will work for jQuery Mobile 1.4.X and above.

$(document).on('pagecontainershow', function (e, ui) {
    var activePage = $(':mobile-pagecontainer').pagecontainer('getActivePage').attr('id');
    if(activePage === 'not-main') {
        //put your code here    
    }
});

This way your code will execute only when that specific page content is initialized. If you want to learn more about page events you should read this answer.

On the other hand, some jQuery Mobile UI elements can get initialized manually but I don't know is it going to work with slider, try to do it like this:

$('#tsetpoint').val(value).slider().slider('refresh'); 

First slider function call will initialize it and second one will refresh it.

Upvotes: 2

Related Questions