0

I am new here, so please pardon any beginner mistakes.

I am learning jQuery (v1.9.1) along with using jQuery Mobile (v1.3.1). I am encountering two problems when using AJAX links and javascript:

1) When I link pages through the default AJAX linking method that jqm offers, I lose the capability of running any newly loaded javascript on the subsequent pages. i.e. When I go from page1.php to page2.php, can I execute javascript namely something like the following (this code is in page2.php):

<script>
$(document).ready(function(){
    $('#form_field_email').focus();
});

</script>

After browsing through bunch of questions here, I believe it is because no new script is evaluated after initial page load. Therefore, I tried to move all my code into on .js file, which I load on page1.php. But sometimes I want to trigger actions on-page-load (as noted above).

Is there any way to achieve this without using eval function?

2) On a similar note, if the id of a DIV on page1.php was 'messageBox', but if I use the same id for another DIV on page2.php, I lose the capability of controlling the newly drawn DIV on page2 as the javascript still points to the old DIV which is no longer visible.

$('#messageBox').show();

Is there a way to use the same name but still be able to point to the elements on the current page.

Thank you for your help.

user3376563
  • 313
  • 1
  • 10
  • 1
    You should never have two element within a document that have the same `id`. If you are adding the elements from the new page and not removing the old ones from the DOM then you should pick a new `id`. – James Montagne Mar 03 '14 at 22:20
  • Also the document.ready event is fired only once and it happens after the browser has finished rendering the page. You should check the documentation for jquery mobile and there surely would be a way to pass a success function either using a callback or via promises. That success function would be executed once the ajax navigation has finished. – Vasil Dininski Mar 03 '14 at 22:24
  • When using _Single page model_ you should place any JS of other page inside `data-role="page"` div. Ajax loads that div only and neglects anything else out of it (head and other elements in body). – Omar Mar 03 '14 at 22:48
  • Here is a simplified explanation of jQM special events http://stackoverflow.com/questions/20457195/setting-up-the-jquery-mobile-script/20459433#20459433 – Omar Mar 03 '14 at 22:56

1 Answers1

0

What you should do is place the code that needs to run after the ajax has loaded in a success callback for the ajax call.

$.ajax({
  url: 'http://example.com',
  success: function() {
    //do something when call completes successfully
  }
);
Nick Barrett
  • 1,051
  • 2
  • 11
  • 28