TheRealChx101
TheRealChx101

Reputation: 1544

Why do I have to refresh my page for a javascript function to work?

I'm developing a mobile site and using jQuery.

When I load a certain page and click the desired button, the code does not execute until I refresh the page. Why is this ?

Here's how I have it

script.js

$(document).ready(function() 
{ 
  $("#user-save").click(
      function(e)
       {
         alert(/clickity-click/);
       });
});

page.php

<html>
   <head>
       <!-- Other jQuery files here -->
      <script src="script.js"></script>
   </head>
<body>
   <div id="user-save" data-role="button">Click me like a boss</div>
</body>
</html>

Upvotes: 0

Views: 6616

Answers (3)

Robotitude
Robotitude

Reputation: 31

I spent several hours rewriting the code on a page that was having this problem, only to realize that the problem was related to the linking/previous page.

The anchor tag and link on the linking/previous page, the one that leads to the page where you would like to ensure $(document).ready(init) will run, needs to have to include data-ajax="false" attribute like this:

<a href="yourpage.html" data-ajax="false"> 

This will ensure that JQuery Mobile doesn't expect that you're loading content dynamically with AJAX, and you are in fact navigating to a different/new page. In other words, JQuery Mobile will only run the $(document).ready() if it is loading a different/new page.

Upvotes: 3

GreyBeardedGeek
GreyBeardedGeek

Reputation: 30088

JQuery Mobile loads pages differently from a 'normal' javascript application. You will typically need to bind to the pageinit event instead of document.ready.

See this previous SO discussion on this topic

Upvotes: 3

Teena Thomas
Teena Thomas

Reputation: 5239

change in these lines:

  1. <script type='text/javascript' src="script.js"></script>
  2. alert('clickity-click');

Upvotes: 0

Related Questions