skip to Main Content

I have a JavaScript program that displays the current date and time in a page title (), then I tried to animate this header as a crawl line, but nothing works. Tried using the slice method, as well as the substring method, but nothing came out of it.

function updateDateTime() {
  let datetime = new Date();
  let datetimeString = datetime.toLocaleString();
  document.title = datetimeString;
}
setInterval(updateDateTime, 1000); // оновлюємо час кожну секунду

updateDateTime();

let marquee = document.getElementById("marquee");
let datetime = document.getElementById("datetime");

function shiftDateTime() {
  const unit = "px";
  let position = Number.parseInt(datetime.style.right) || 0;
  let width = datetime.offsetWidth;

  position = position > marquee.offsetWidth ?
    -width :
    position + 1;

  datetime.style.right = position + unit;
  requestAnimationFrame(shiftDateTime);
}

shiftDateTime();
<!DOCTYPE html>
<html>

<head>
  <title>Date&Time marquee</title>
</head>

<body>
  <div id="marquee">
    <span id="datetime"></span>
  </div>
</body>

</html>

Here’s my code, all I was able to do was display the current date and time in the title. In the end, our program should display the current date and time in the page title and animate them as a running line right-to-left. How can I do that?

2

Answers


  1. Just add a space at each iteration:

    let i = 0;
    function updateDateTime() {
      const datetime = new Date();
      const datetimeString = datetime.toLocaleString();
      const trailingSpaces = Array(i).fill().map(_=>' ').join('');
      document.title = trailingSpaces + datetimeString;
      i = (i + 1) % 10;
    }
    setInterval(updateDateTime, 100);
    <!DOCTYPE html>
    <html>
    
    <head>
      <title>Date&Time marquee</title>
    </head>
    
    <body>
      <div id="marquee">
        <span id="datetime"></span>
      </div>
    </body>
    
    </html>
    Login or Signup to reply.
  2. first space chraracters can’t be used in a html title element.
    you may use a _ instead.

    let tittlemov = 0;
    setInterval(()=>
      { 
      document.title = '_'.repeat(tittlemov++) 
                     + new Date().toLocaleString() 
                     + '_'.repeat(10 - tittlemov);
      tittlemov %= 10;
      }, 1000 );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search