Home > front end >  Uncaught ReferenceError: showtime is not defined
Uncaught ReferenceError: showtime is not defined

Time:09-02

I am trying to create a digital clock for the web page

My controller looks like this:

body tag:

<body onl oad="showtime()">
     <h1></h1>
</body>

script :

<script src="text/javascript">

function showtime(){
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
var session = "AM";

if (h > 12){
    h = h - 12;
    //h = 13 - 12 = 1
}
if (h>=12){
    session = "PM"
}

h = h < 10 ? "0"   h : h;
m = m < 10 ? "0"   m : m;
s = s < 10 ? "0"   s : s;

var time = h   " : "   m   " : "   s   " : "   session;
document.getElementsByTagName('h1')[0].innerText = time;
setTimeout(showtime,1000);

}

now when I check my console the error I get is:

Digital Clock.html:16 Uncaught ReferenceError: showtime is not defined

CodePudding user response:

<script src="text/javascript">

The src attribute of a script tag specifies the script location (URI) https://developer.mozilla.org/es/docs/Web/SVG/Element/script#attr-src

I think you meant to use the type attribute

<script type="text/javascript">

CodePudding user response:

Use DOMContentLoaded event instead of calling your function from the body tag

i dont recommend use tag selectors you can give the h1 an id to prevent issues when you have multiple elements which had the same tag.

window.addEventListener('DOMContentLoaded', showtime);
    
function showtime(){
  let d = new Date(),
      h = d.getHours(),
      m = d.getMinutes(),
      s = d.getSeconds(),
      session;
      
   session = (h >= 12) ? "PM" : "AM";
   if (h > 12) h -= 12;
   
   h = h < 10 ? "0"   h : h;
   m = m < 10 ? "0"   m : m;
   s = s < 10 ? "0"   s : s;

  document.querySelector('#header').innerText = `${h}:${m}:${s} ${session}`;
  setTimeout(showtime,1000);
}
<body>
  <h1 id="header"></h1>
  <script type="text/javascript" src="your javascript path"></script>
</body>

Or use the old code, it will works as well

window.addEventListener('DOMContentLoaded', showtime);
    
function showtime(){
  var d = new Date();
  var h = d.getHours();
  var m = d.getMinutes();
  var s = d.getSeconds();
  var session = "AM";

  // Use this statement first, because in that case you never have a PM session
  if (h>=12){
      session = "PM"
  }
  
  if (h > 12){
      h = h - 12;
      //h = 13 - 12 = 1
  }

  h = h < 10 ? "0"   h : h;
  m = m < 10 ? "0"   m : m;
  s = s < 10 ? "0"   s : s;

  var time = h   " : "   m   " : "   s   " : "   session;
  document.getElementsByTagName('h1')[0].innerText = time;
  setTimeout(showtime,1000);
}
<body>
  <h1></h1>
  <script type="text/javascript" src="your javascript path"></script>
</body>

CodePudding user response:

Just replace "src" by "type" in the script tag, like this :

<script type="text/javascript">
  • Related