TransWikia.com

Best practice to update background image depending on the time of day without needing to refresh the page

Stack Overflow Asked by Greenie on December 27, 2021

So I just did a dynamic landing page tutorial by Brad Traversy. It’s a great tutorial but I want to achieve the same thing without having to refresh the page to see the background image change when the hour is < 12, < 16 or otherwise as specified in the code below. More than that I want to know the best or most appropriate practise for achieving this rather than doing it in any way possible.

https://codepen.io/bradtraversy/pen/XLrQvz

If further clarification on my question is needed please ask.

Thank you.

HTML


<time id="time"></time>
    <h1>
      <span id="greeting"></span>
      <span id="name" contenteditable="true"></span>
    </h1>

    <h2>What Is Your Focus For Today?</h2>
    <h2 id="focus" contenteditable="true"></h2>


JS

// DOM Elements
const time = document.getElementById('time'),
  greeting = document.getElementById('greeting'),
  name = document.getElementById('name'),
  focus = document.getElementById('focus');

// Options
const showAmPm = true;

// Show Time
function showTime() {
  let today = new Date(),
    hour = today.getHours(),
    min = today.getMinutes(),
    sec = today.getSeconds();

  // Set AM or PM
  const amPm = hour >= 12 ? 'PM' : 'AM';

  // 12hr Format
  hour = hour % 12 || 12;

  // Output Time
  time.innerHTML = `${hour}<span>:</span>${addZero(min)}<span>:</span>${addZero(
    sec
  )} ${showAmPm ? amPm : ''}`;

  setTimeout(showTime, 1000);
}

// Add Zeros
function addZero(n) {
  return (parseInt(n, 10) < 10 ? '0' : '') + n;
}

// Set Background and Greeting
function setBgGreet() {
  let today = new Date(),
    hour = today.getHours();

  if (hour < 12) {
    // Morning
    document.body.style.backgroundImage = "url('https://i.ibb.co/7vDLJFb/morning.jpg')";
    greeting.textContent = 'Good Morning, ';
  } else if (hour < 18) {
    // Afternoon
    document.body.style.backgroundImage = "url('https://i.ibb.co/3mThcXc/afternoon.jpg')";
    greeting.textContent = 'Good Afternoon, ';
  } else {
    // Evening
    document.body.style.backgroundImage = "url('https://i.ibb.co/924T2Wv/night.jpg')";
    greeting.textContent = 'Good Evening, ';
    document.body.style.color = 'white';
  }
}

// Get Name
function getName() {
  if (localStorage.getItem('name') === null) {
    name.textContent = '[Enter Name]';
  } else {
    name.textContent = localStorage.getItem('name');
  }
}

// Set Name
function setName(e) {
  if (e.type === 'keypress') {
    // Make sure enter is pressed
    if (e.which == 13 || e.keyCode == 13) {
      localStorage.setItem('name', e.target.innerText);
      name.blur();
    }
  } else {
    localStorage.setItem('name', e.target.innerText);
  }
}

// Get Focus
function getFocus() {
  if (localStorage.getItem('focus') === null) {
    focus.textContent = '[Enter Focus]';
  } else {
    focus.textContent = localStorage.getItem('focus');
  }
}

// Set Focus
function setFocus(e) {
  if (e.type === 'keypress') {
    // Make sure enter is pressed
    if (e.which == 13 || e.keyCode == 13) {
      localStorage.setItem('focus', e.target.innerText);
      focus.blur();
    }
  } else {
    localStorage.setItem('focus', e.target.innerText);
  }
}

name.addEventListener('keypress', setName);
name.addEventListener('blur', setName);
focus.addEventListener('keypress', setFocus);
focus.addEventListener('blur', setFocus);

// Run
showTime();
setBgGreet();
getName();
getFocus();


CSS

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  font-family: 'Quicksand', sans-serif;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  height: 100vh;
  color: black;
}

#time {
  font-size: 8rem;
}

h1 {
  margin-bottom: 3rem;
}

h2 {
  margin-bottom: 0.5rem;
  opacity: 0.6;
}

@media (max-width: 700px) {
  #time {
    font-size: 6rem;
  }
}

One Answer

Here is a solution modifying just the setBgGreet function:

// Set Background and Greeting
function setBgGreet() {
  let today = new Date(),
    hour = today.getHours();
  
  const now = today.getTime(); // this is the current time represented in milliseconds
  let nextChange; // this variable will tell when the next change of bg should occur

  if (hour < 12) {
    // Morning
    document.body.style.backgroundImage = "url('https://i.ibb.co/7vDLJFb/morning.jpg')";
    greeting.textContent = 'Good Morning, ';
    nextChange = today.setHours(12, 0, 0, 0); // Next change will be at 12 today
  } else if (hour < 18) {
    // Afternoon
    document.body.style.backgroundImage = "url('https://i.ibb.co/3mThcXc/afternoon.jpg')";
    greeting.textContent = 'Good Afternoon, ';
    nextChange = today.setHours(18, 0, 0, 0); // Next change will be at 18 today
  } else {
    // Evening
    document.body.style.backgroundImage = "url('https://i.ibb.co/924T2Wv/night.jpg')";
    greeting.textContent = 'Good Evening, ';
    document.body.style.color = 'white';
    nextChange = today.setHours(24, 0, 0, 0); // Next change will be at midnight, going to tomorrow
  }

  setTimeout(setBgGreet, nextChange - now); // This timeout will wait the correct amount of time
                                            // and then will trigger this very same function again
}

Answered by Pedro Lima on December 27, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP