February 28, 2013

JavaScript do not execute in jquery mobile

Recently, I receive a question about why javascript do not execute in jquery mobile when using
<a href="aboutus.html">About US<a> in home.html.

It is because jquery Mobile will intercept the <a> tag and use AJAX to get the HTML to navigate the page instead of changing page directly. This result the javascript in "aboutus.html" will not execute. Let's see an example:

This is home.html

<!DOCTYPE html>
<html>
<head>
 <title>Home</title>
 <meta name="viewport" content="width=device-width, initial-scale=1" />
 <meta charset="utf-8">
 <link rel="stylesheet" href="jquery.mobile-1.2.0.min.css" />
 <script src="jquery-1.8.2.min.js"></script>
 <script src="jquery.mobile-1.2.0.min.js"></script>
 <script src="phonegap-1.4.1.js"></script>
</head>

<body onload="onBodyLoad()">
    <div data-role="header" data-id="aboutus" data-position="fixed">
        Home
    </div>
 <div data-role="header">
  <a href="aboutus.html">About US<a>
 </div>
 
</body>
</html>

This is aboutus.html

<!DOCTYPE html>
<html>
<head>
 <title>About us</title>
 <meta name="viewport" content="width=device-width, initial-scale=1" />
 <meta charset="utf-8">
 <link rel="stylesheet" href="jquery.mobile-1.2.0.min.css" />
 <script src="jquery-1.8.2.min.js"></script>
 <script src="jquery.mobile-1.2.0.min.js"></script>
 <script src="phonegap-1.4.1.js"></script>
 <script type="text/javascript">

  function onBodyLoad()
  {
   document.addEventListener("deviceready", onDeviceReady, false);
  }

  function onDeviceReady()
  {
   alert("testing");
  }
 </script>

</head>

<body onload="onBodyLoad()">
    <div data-role="header" data-id="aboutus" data-position="fixed">
        About us
    </div>
</body>
</html>
In order to fix this issue, you would add rel="external" data-ajax="false" to make it refresh and go to the page directly instead of AJAX.

<a href="aboutus.html" rel="external" data-ajax="false">About US</a>

2 comments: