0

I'm getting grey haired here because I can't get this clock to display on my SPA. I'm haveing a clock that should be displayed on the page but I can't seem to get it right. I have tried the things we were taught at the course but I can't seem to get it right. Could you please take a look at it and lend a hand perhaps. Not even the console.log is printed out.

Code in Clock.js:

function clock () {
  let now = new Date()
  let h = now.getHours()
  let m = now.getMinutes()
  let s = now.getSeconds()

  m = checkTime(m)
  s = checkTime(s)

  let target = document.querySelector('#footer-clock')
  let clockText = document.createTextNode(h + ':' + m + ':' + s)
  target.appendChild(clockText)

  setInterval(clock, 500)
}

function checkTime (i) {
  if (i < 10) {
    i = '0' + i
  }
  return i
}

module.exports = clock

Code in app.js:

const clock = require('./clock.js')

document.querySelector('#footer-clock').onload = function () {
  clock()
  console.log('Loaded')
}

And in HTML I have:

footer>
  <div id="footer-clock">

  </div>
</footer>
Thomas Bengtsson
  • 399
  • 2
  • 10
  • 22
  • 1
    Possible duplicate of [How to add onload event to a div element?](https://stackoverflow.com/questions/4057236/how-to-add-onload-event-to-a-div-element) – jmargolisvt Dec 21 '17 at 17:52
  • 1
    Beyond the onload issue, you are also appending a new timestamp every invocation of `clock`. Instead you might just want to do `target.textContent = h + ':' + m + ':' + s`. Further, you call `setInterval`, which will make the invocations explode. You probably want `setTimeout`. – vox Dec 21 '17 at 17:55
  • https://fiddle.jshell.net/v1yjftoj/ – Roy Bogado Dec 21 '17 at 17:59
  • @Roy Works fine, now I just need to get to load when the page is loaded... – Thomas Bengtsson Dec 21 '17 at 18:05

1 Answers1

1

The browser doesn't understand what

module.exports = {}
const clock = require('./clock.js')

this will work when you use something like webpack for bundling and using commonjs Module also if you look at the console in devtools in chrome you will see this error

Uncaught ReferenceError: require is not defined

note that : when you developing sites using html you should put any scripts in the script tag like this

<script src="app.js"></script>
<script src="clock.js"></script>

now the code in clock.js will be available any where so in app.js you can call the method without require function

clock()

also you need to use window.onload instead of

document.querySelector('#footer-clock').onload = function () {
clock()
console.log('Loaded')
}

here you can learn more about global events

mostafa tourad
  • 4,308
  • 1
  • 12
  • 21