Utilizing conditional statements and time to dynamically alter the class of an object

I need to change the class of an object based on the time, with two classes available: recommendedspot and notrecommended. The code I've written so far is not displaying the image correctly. Can someone help me troubleshoot this issue?

Here is my current code:

var time = new Date().getHours();
if (time > 9 && time < 17) {
  document.getElementById("spotsouth").classList.remove('notrecommended');
  document.getElementById("spotsouth").classList.add('recommendedspot');
} else if (time > 6 && time < 9) {
  document.getElementById("spotnorth").classList.remove('notrecommended');
  document.getElementById("spotnorth").classList.add('recommendedspot');
} else if (time > 17 && time < 21) {
  document.getElementById("spotnorth").classList.remove('notrecommended');
  document.getElementById("spotnorth").classList.add('recommendedspot');
} else {}
.notrecommended {
  display: none;
}

.recommendedspot {
  display: inline;
  margin-left: 15px;
  max-width: 50px;
}
<img id="spotsouth" src="site-logo.png" alt="spot south" class="notrecommended">
<img id="spotnorth" src="site-logo.png" alt="spot north" class="notrecommended">

If you spot where I went wrong, please share your insights as I am struggling to resolve this issue. Thank you in advance.

Answer №1

It's clear that the issue lies in the comparisons not aligning with your desired outcome, as others have pointed out. Additionally, there seems to be a missing piece of logic: recommending something in one time slot requires removing it from another if you don't want both to show simultaneously.

This solution provides testable code that is easier to comprehend.

To test this solution, simply replace new Date.getHours() with actual numbers to observe its effects on the outcome.

function promote(element) {
  element.classList.remove('notrecommend');
  element.classList.add('recommendedspot');
}

function demote(element) {
  element.classList.remove('recommendedspot');
  element.classList.add('notrecommend');
}

function processElements(time) {
  var southSpot = document.getElementById("spotsouth")
  var northSpot = document.getElementById("spotnorth");

  var inMorning = time >= 6 && time < 9;
  var inWorkTime = time >= 9 && time < 17;
  var inEvening = time >= 17 && time <= 21

  if (inWorkTime) {
    promote(southSpot);
    demote(northSpot);
  } else if (inMorning || inEvening) {
    promote(northSpot);
    demote(southSpot);
  } else {
    // This section of the code handles scenarios outside of the known time slots. In this instance, it hides both elements, but other combinations are possible.
    demote(southSpot);
    demote(northSpot);
  }
}

processElements(new Date().getHours());

// Test with specific numbers to observe changes, such as 1, 6, 8, 9, 12, 17, 19, 21:
// processElements(1);
.notrecommended {
  display: none;
}

.recommendedspot {
  display: inline;
  margin-left: 15px;
  max-width: 50px;
}
<img id="spotsouth" src="site-logo.png" alt="spot south" class="notrecommended">
<img id="spotnorth" src="site-logo.png" alt="spot north" class="notrecommended">

Answer №2

Make sure to manage the time intervals properly using the code snippet below:

`var currentTime = new Date().getHours();
 if (currentTime >= 9 && currentTime < 17) {
   document.getElementById("spotsouth").classList.remove('notrecommended');
   document.getElementById("spotsouth").classList.add('recommendedspot'); 
 } else if (currentTime > 6 && currentTime < 9) {
   document.getElementById("spotnorth").classList.remove('notrecommended');
   document.getElementById("spotnorth").classList.add('recommendedspot');
 } else if (currentTime >= 17 && currentTime < 21) {
   document.getElementById("spotnorth").classList.remove('notrecommended');
   document.getElementById("spotnorth").classList.add('recommendedspot');
} else {}`

Ensure that the time is handled correctly for values equal to 6, 17, and 9.

Hopefully, this solution will be beneficial.

Answer №3

It's important to address the equalities, such as when your time is at 6/9/17/21. Handling these equalities will help solve any issues that may arise.

Answer №4

Here is a different approach utilizing javascript case with just one html element. It effectively displays the correct image based on the current time and also accounts for time frames outside the specified parameters (such as night time).

update included an alternative switch since some individuals view switch (true) as unfavorable behavior. This alternative first identifies the appropriate timeframe.

var imgNorth = 'url/to/north.png';
var imgSouth = 'url/to/south.png';
var imgClose = 'url/to/close.png';

var image  = document.getElementById("image");
var image2 = document.getElementById("image2");

var time = new Date().getHours();

/* Solution */

switch (true) { // conditional switch, some folks don't like this
   case (time >=  6 && time <   9): // Between 6 and 9
   case (time >= 17 && time <= 21): // Between 17 and 21
       image.src = imgNorth;
       image.alt = 'spot north';
       break;

   case (time >= 9 && time < 17): // Between 9 and 17
       image.src = imgSouth;
       image.alt = 'spot south';
       break;

   case (time < 6 || time > 21): // ??
       image.src = imgClose; // No seats? closed? stand only??
       image.alt = 'closed';
       break;
};


/* Alternate */

// Get timeframe
var timeFrame =  (time >=  6 && time <   9) ? 1 :
                ((time >= 17 && time <= 21) ? 2 :
                ((time >=  9 && time <  17) ? 3 : 4 ));                 

switch (timeFrame) { // fall-through switch check, preferred
    case 1:
    case 2: // Between 6 and 9 or between 17 and 21
        image2.src = imgNorth;
        image2.alt = 'spot north';
        break;

    case 3: // Between 9 and 17
        image2.src = imgSouth;
        image2.alt = 'spot south';
        break;

    case 4: // ??
        image2.src = imgClose; // No seats? closed? stand only??
        image2.alt = 'closed';
        break;
};
<img id="image" src="site-logo.png" alt=""><br>
<img id="image2" src="site-logo.png" alt="">

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

Ways to integrate PHP MySQL with NodeJS and SocketIO

Currently, I am working on developing a chat application. I have successfully implemented features like creating accounts, logging in, selecting, viewing, and more using PHP MySQL. Now, I am venturing into the Instant Messaging aspect by utilizing NodeJS a ...

Retrieve the ID of the image element using Jquery from a collection of images within a div container

I'm encountering a simple issue that I can't seem to solve. I am working on a basic slider/gallery with the following functionalities: 1) "If button 1 is clicked, image one will appear." 2) "Clicking on button 2 will make IMAGE 1 slide left and I ...

How to Display HTML Content from a WYSIWYG Editor in ASP.NET Webforms without Master Page Bootstrap Styles Interfering

I am facing an issue in ASP.NET Webforms with a Master Page that imports Bootstrap CSS, which is then used by all child pages of the site. One of the child pages contains HTML content generated from a WYSIWYG editor. However, the styles applied by Bootstr ...

Some browsers are failing to display the navigation bar on my website

After working on my website, www.alexanderpopov.org, I encountered an issue with the navigation bar disappearing on some computers and browsers. I'm using css to style it, but the problem persists. Below is the HTML code for your reference. Any advice ...

'jQuery' is not recognized as defined, error no-undef

I am currently working on a file that utilizes jQuery for testing purposes: (function($) { "use strict"; // Start of use strict // Configure tooltips for collapsed side navigation $('.navbar-sidenav [data-toggle="tooltip"]').tooltip({ ...

Nunjucks not loading the script when moving from one page to another

Currently, I am in the process of developing a website utilizing nunjucks and express. This website serves as a blog platform with content sourced from prismic. My goal is to load a script file for an active campaign form whenever a user navigates from a b ...

Having trouble getting my angular form validation to function properly

Even though I disabled Bootstrap's validation while using Angular, the validation for every input field still doesn't work. It seems like I have everything set up correctly. My code looks like this below with no success on input validation: < ...

Encountering a problem with the JavaScript promise syntax

Using pdfjs to extract pages as images from a PDF file and then making an AJAX call to send and receive data from the server is proving to be challenging. The implementation for iterating through the pages in the PDF was sourced from: The issue lies in pr ...

Pandas will provide the following Sunday date for each row

I'm working with a dataset in Pandas for Python that includes a column of datetime values. I am looking to create a new column that specifically contains the date of the upcoming Sunday for each entry. So far, my attempts have involved using iterrows ...

Sorting nested table rows in vueJS is an essential feature to enhance

I am working with a json object list (carriers) that looks like this: https://i.stack.imgur.com/0FAKw.png Within my *.vue file, I am rendering this using the following code: <tr v-for="carrier in this.carriers"> <td>{{ carrier.id ...

Integrating objects into the <select> element through the combination of C#, JavaScript, and HTML connected to a SQL

Can someone assist me in resolving this issue? I am trying to populate an HTML element with database fields using C# and JavaScript, but so far my code is not producing any output. I have also attempted to include a button that calls the "loadGrp" function ...

Is there a way to handle specific email format designs with PHP?

When trying to send an email with specific shipping information and tracking numbers, the formatting appears strange. Here is the desired format: Dear xyz , Per your request, this email is to no ...

Tips for implementing React Browser Router within Material UI Drawer

I'm currently exploring how to implement Browser Router in React to populate the content section of a Material UI Drawer. While my code successfully links menu options to components displayed within the drawer's content section, a problem arises ...

What technique is used in this CSS code to give each line of text a unique horizontal color gradient?

I stumbled upon a fascinating jsfiddle that can create color gradients on specific lines of text. Each line has a unique two-color gradient applied in a consistent pattern: Black to Red, Red to Black, Black to Blue, and Blue to Black. Despite its intrigui ...

"React-router is successfully updating the URL, however, the component remains un

I am currently working on a React application that includes a form for users to fill out. Once the user clicks the submit button, I want them to be redirected to a completely different page. Although I have only focused on the visual design at this point a ...

What is the process of replacing fetch with JavaScript?

Looking to test my React application and mock the backend calls, I made the decision to swap out fetch with a Jest function that returns a static value. The issue I encountered was my inability to override the default fetch behavior. After some research, ...

Switching from HTML to PHP programming

Trying to build a website from scratch and incorporate a form has been challenging. My goal is for the Submit button to send an email without launching any email program, but I'm facing redirection issues. Despite searching on Google for solutions, I ...

Is QA supported by LG WebOS 3.5 through webdriver?

I've been experimenting with Javascript ( nodejs ) and have successfully automated browser operations using selenium-webdriver on a local server. However, I am facing challenges when trying to automate tasks on my LG WebOS 3.5 TV. Does anyone know how ...

Steps for inputting time as 00:00:00 in MUI's X DateTimePicker

React:18.2.0 mui/material: 5.10.5 date-fns: 2.29.3 date-io/date-fns: 2.16.0 formik: 2.2.9 I'm facing an issue with using DateTimePicker in my project. I am trying to enter time in the format Hour:Minute:Second, but currently, I can only input 00:00 f ...

Website Translator

I'm currently working on a website that needs to be available in two languages. One option is to do our own translations, but that could end up requiring more time for development. That's why I am exploring the possibility of finding a suitable ...