Search code examples
javascriptmonaca

Monaca Javascript not working


I have the following code and the simple js shown is not working. How do I make js work in monaca?

Here is the code for what I am doing.

I have added jQuery (Monaca Version) Version: 2.0.3 from the config screen, by the way.

<!DOCTYPE HTML>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <meta http-equiv="Content-Security-Policy" content="default-src * data:; style-src * 'unsafe-inline'; script-src * 'unsafe-inline' 'unsafe-eval'">
  <script src="components/loader.js"></script>
  <script src="lib/onsenui/js/onsenui.min.js"></script>

  <link rel="stylesheet" href="components/loader.css">
  <link rel="stylesheet" href="lib/onsenui/css/onsenui.css">
  <link rel="stylesheet" href="lib/onsenui/css/onsen-css-components.css">
  <link rel="stylesheet" href="css/style.css">

  <script>
    //this starts the count down. 
    //time should be in seconds
    function countDown(time){
        $("#countDown").txt(time);
        var timeout=setTimeout(function(){
            time--;
            $("#countDown").txt(time);
            if(time==0) clearTimeout(timeout);
        }, 1000);
    }

    ons.ready(function() {
        countDown(10);
    });

  </script>
</head>
<body>
    <div id="countDown"></div>
</body>
</html>

Solution

  • From what I see in your code, you've made a typo in assigning the value of the time variable to the <div> element. It is not $("#countDown").txt(time);, it's $("#countDown").text(time);.

    Also, judging from the name of your function - countdown I'm guessing you are trying to create a counter appearing on the screen. In that case you should not be using the setTimeout(function, period) function, as this is used to call the function passed as its argument, only once after the period (passed as the second argument) passes. Therefore, you should use the setInterval(function(),period) function, which calls the function every time the period passes. Accordingly you should use clearInterval() instead of clearTimeout().

    Your code should look something like this:

    <script>
        //this starts the count down. 
        //time should be in seconds
        function countDown(time){
            $("#countDown").text(time);
            var timeout=setInterval(function(){
                time--;
                $("#countDown").text(time);
                if(time==0) clearInterval(timeout);
            }, 1000);
        }
    
        ons.ready(function() {
            countDown(10);
        });
    </script>