3

I'm using Cordova/PhoneGap and Onsen UI. I have two html pages. Switch(pushpage) button is working perfect. But Javascript not working in search.html

Here is my code:

  • index.html (Default Main Page)
  • search.html

index.html

...
<body>

<ons-navigator title="Navigator" var="myNavigator">
<ons-button
        onclick="myNavigator.pushPage('search.html', { animation: 'lift' })">
        Switch Page
</ons-button>
</ons-navigator>
</body>

search.html

<ons-page>
<script>
alert('Testing Javascript');
</script>
</ons-page>
user1999
  • 87
  • 1
  • 10

2 Answers2

4

The search.html page is inserted dynamically when myNavigator.pushPage('search.html') is called.

When a <script> tag is inserted in this way the code is not executed.

Please refer to this question for more info: Can scripts be inserted with innerHTML?

In order to execute some script when a page is pushed you can use the postpush event:

ons.ready(function() {
  myNavigator.on('postpush', function() {
    alert('Hello, world!');
  });
});
Community
  • 1
  • 1
Andreas Argelius
  • 3,604
  • 1
  • 13
  • 22
2

It would be better if you put all the JavaScript in js files and call the function when you click the button, for example:

HTML

<body>
  <ons-navigator title="Navigator" var="myNavigator">
    <ons-button
        onclick="myNavigator.pushPage('search.html', { animation: 'lift' }); callAlert();">
        Switch Page
    </ons-button>
  </ons-navigator>
</body>

JS

function callAlert() {
  alert('Testing Javascript');
};

Alternatively, you can use ons-navigator events, like postpush, to personalize your code even more, you can take a look at them HERE

Andi Pavllo
  • 2,506
  • 4
  • 18
  • 30