Interested in creating a weather application that changes color based on the time of day

My attempt to create a weather app with a glowing effect has hit a roadblock. I want the app to glow "yellow" between 6 and 16 hours, and "purple" outside of those hours. I have assigned classes for AM and PM elements in HTML, and styled them accordingly in CSS. But, my JavaScript function isn't working as expected. It only recognizes one class (the last one added – PM) and not the other (AM). Below is a snippet of my HTML and JS code. (P.S. Bootstrap is being used)

HTML

 <body>
    <div id="weather-app-wrapper">
      <div class="container-lg mt-5 mb-2 am pm" id="weather-app">
        <div class="row">
          <div class="col-12 mt-3">
            <form id="city-search-form">
              <input
                type="text"
                placeholder="Enter city name"
                id="search-field"
              />
              <input type="submit" value="search" class="btn btn-primary" />
            </form>
          </div>
        </div>

JAVASCRIPT

let now = new Date();
let currentDate = document.getElementById("date-element");

let date = now.getDate();
let hours = now.getHours().toString().padStart(2, "0  ");

let minutes = now.getMinutes().toString().padStart(2, "0");

let days = [
  "Sunday",
  "Monday",
  "Tuesday",
  "Wednesday",
  "Thursday",
  "Friday",
  "Saturday",
];
let day = days[now.getDay()];

let months = [
  "January",
  "Febuary",
  "March",
  "April",
  "May",
  "June",
  "July",
  "August",
  "September",
  "October",
  "November",
  "December",
];
let month = months[now.getMonth()];
currentDate.innerHTML = `${day}, ${month} ${date},  ${hours}:${minutes}`;

function glow() {
  let app = document.getElementById("weather-app");
  if (hours > 6 && hours < 16) {
    app.classList.add("am");
  } else {
    if (hours < 6 && hours >= 16) {
      app.classList.add("pm");
    }
  }
}
glow()

I've experimented with different versions of the code above, but being a beginner in coding, I might be missing something crucial that could solve this issue. Any basic and simple guidance would be greatly appreciated, as I'm still learning.

If I haven't provided enough information about my problem or included too much unnecessary detail, I apologize in advance!

Thank you for your help!

Answer №1

It appears that the glow function was not executed. Feel free to inform me if my assumption is incorrect.

Answer №2

Just like Konrad suggested, it's important to remove the am and pm classes from the HTML in order to properly add the correct one, avoiding having both at the same time. Additionally, there seems to be a mistake in the else part of the if statement in the glow function:

if (hours < 6 && hours >= 16) {
  app.classList.add("pm");
}

This logic implies that it will be pm only if hours are less than 6 and greater than or equal to 16 simultaneously, which is never true. However, considering the first if statement, removing the if statement in the else clause would resolve the issue in 'glow'.

function glow() {
  let app = document.getElementById("weather-app");
  if (hours > 6 && hours < 16) {
    app.classList.remove("pm");
    app.classList.add("am");
  } else {
    app.classList.remove("am");
    app.classList.add("pm");
  }
}

On a side note, shouldn't am be when hours < 12?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unspecified error encountered in the VUE selection view

I am facing an issue with the undefined value in the select view while attempting to add a new project. Could you suggest a solution? I tried using v-if but it didn't work for me. This is how my code looks: <v-select v-model="pro ...

Postback does not reload all controls in the NameValueCollection

Recently, I designed a custom User Control in asp.net. public class InputMask : CompositeControl, IPostBackDataHandler, IPostBackEventHandler Imagine the custom control is enclosed within a div element: <div runat="server" id="inputArea"> < ...

Transmitting JSON AJAX response to populate location markers on Google Maps

When a button is clicked, an AJAX response is triggered to display JSON data based on a search query. My goal is to take the all_locations variable from the AJAX response and use it to show markers on a Google map. I'm uncertain about how to achieve t ...

What is preventing Google Chrome from locating my app.js file?

Just embarking on my journey to learn Nodejs through a basic app. Strangely, Google Chrome is unable to locate my app.js file in the /assets/js.app directory. https://i.sstatic.net/Eu8FG.png Reviewing the paths I've configured, it seems everything i ...

Errors are being thrown by 'npm run serve' due to the absence of FilterService

I've been working on a project using Vue.js and I keep running into an issue with npm. Every time I install it, I get errors saying that certain files are missing from the node_modules folder. When I try to run npm run serve, I encounter the followin ...

Differences between HTML and JSON data in AJAX response

Currently, I am facing a challenge in loading data on the frontend and displaying it. One option is to retrieve the data as a JSON object and generate HTML elements based on it. The alternative approach involves fetching HTML data directly from the backend ...

Creating an anchor element with text and a bootstrap icon involves using the appropriate HTML structure and

I am trying to figure out how to create an element that includes both text and a Bootstrap icon. Here is the HTML code: <a> Edit <i class="icon-pencil" /> </a> Can anyone help me understand how to select this DOM element using jQuer ...

Validating alpha-numeric passwords with JavaScript

I created a JavaScript function to validate if a password is alphanumeric. However, I am facing an issue where the alert message is not being displayed when the password is not alphanumeric. Below is my code snippet: if (!input_string.match(/^[0-9a-z]+$ ...

The Battle of Naming Styles in HTML and CSS: CamelCase versus Underscores

After reading numerous articles discussing the pros and cons of camelCase and Underscore naming conventions, I have always leaned towards camelCase due to its byte-saving nature. However, upon discovering BEM, I must admit that I am now in a state of conf ...

Can someone please help me convert this jQuery code into vanilla JavaScript?

My Cordova app has an email sending function that utilizes jQuery. During debugging, the ajax function works perfectly in my browser, but once I build the app and test it on my phone, it stops working. I encountered a similar issue before, which was resolv ...

Error in public build of Gatsby & Contentful site due to incorrect file paths

Encountering difficulties while attempting to deploy a Gatsby site with Contentful CMS. Development mode runs smoothly, but issues arise during the build process. Upon executing the Gatsby build command, the site is deployed successfully initially. Howeve ...

Guide to retrieving a file stored locally with VueJS

Currently, I am working on an upload system and I want to provide users with a sample template. The template is stored locally in a subfolder within the assets directory. My goal is to access this template in my VueJS component and display a link to it on ...

Seamless animation with Angular 4

I'm working on creating a dynamic Homepage in Angular 4 with various cards such as stats, charts, etc., all enhanced with animations. One interesting feature I've implemented is the ability to toggle chart cards to expand to full screen by clicki ...

The android webview is having trouble loading HTML that includes javascript

I have been attempting to showcase a webpage containing HTML and JavaScript in an android webview using the code below. Unfortunately, it doesn't seem to be functioning properly. Can someone provide assistance? Here is the code snippet: public class ...

Combining CSR and SSR in the next iteration of our project will

In my application, I have three main user roles: Consumer, Merchant, and Admin. I want the pages that Consumers access to be SEO friendly and server rendered. However, for Merchants and Admins, I prefer them to be client rendered with their own respective ...

CSS photo display with magnification feature

I currently have a functioning inner-zoomable image set up with the code provided. I am interested in converting this setup into an image gallery with zoom capabilities for the selected image element, but I'm unsure where to start. My objective is to ...

Can a value of a variable be "stored" in NodeJS?

I am working on a website that allows clients to make their site go live by setting var live = true;. Once this variable is set, certain webpages will display. I would prefer not to store the live variable in a database as creating a collection solely fo ...

Is it possible for me to ensure that the argument passed to `res.write` is sent as one solid chunk?

When utilizing express' res.write method to send chunks back to the requestor, it is important to note that one call to res.write does not necessarily mean the argument passed will be received as a single chunk. This can complicate the process of pars ...

Is there a way to establish a universal font for all apps within ant design?

I am currently working with NextJS version 14 and I have the following setup: In my globals.css file, I have imported a Google font like so: @import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@100;200;300;400;500;600;700;800& ...

What is the purpose of deserializing the user for every request using PassportJS?

While I have scoured the official documentation and various online resources, I am still unable to find a solution to what seems like an obvious question. When working with Passport.js, it is necessary to define two methods - one for serializing and one f ...