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

Tips for creating a dashed border line that animates in a clockwise direction when hovering

I currently have a dashed border around my div element: .dash_border{ border: dashed; stroke: 2px; margin:20px; } My goal is to make the dashed lines move clockwise when my pointer hovers over the div element and stop moving ...

Exploring the principles of object-oriented design within the context of Node

I am facing challenges with the asynchronous flow of Node.js. Let's assume we have the following class: function myClass() { var property = 'something'; var hasConnected = false; this.connect = function(params) { // Logic to conn ...

Enhancing React Performance: Storing Component Identity in Redux State

Can I safely pass this to a Redux action creator from a component defined using React.createClass? In my code, I have created the following reducer: const unsavedChangesProtectionReducer = handleActions({ [ENABLE_UNSAVED_CHANGES_PROTECTION]: (unsaved ...

Message displayed within Ng-repeat loop

Having trouble implementing a tooltip within an ng-repeat for each item in a td element. Whenever the mouse hovers over an item inside the td, I want a tooltip to display with more details. The code below shows my setup, using ng-if to prevent displaying e ...

Struggling to align a div vertically using CSS is causing me some difficulties

Hey there, I'm trying to figure out how to align the "container2" div to the bottom of the "container," but I'm running into some issues. Can anyone lend a hand? HTML <div id="container"> <div id="container2"> ...

Utilizing the Jquery hover feature to reveal or conceal an element

My Hover function is designed to display and hide sub menus when a person hovers on them. The issue I'm facing is that the menu disappears when I move the mouse down towards it. Can someone help me identify what I am doing wrong here? ...

Unable to load the manually added module in the /node_modules/ folder

I'm trying to manually use a module that I placed in the /node_modules/ directory. After copying and pasting the files and installing dependencies with npm, I encountered an issue while using NWJS 0.16.0. When attempting var speech = require('sp ...

Tips on altering the quantity of columns in a ul list dynamically

I'm trying to create a list with 2 columns, and I want it to switch to 3 columns when the browser window is wide enough (for example, on a 23 inch monitor). Can this be achieved using CSS or any other method? Here is my current CSS: .search-results ...

Managing various encoding methods when retrieving the XML data feed

I'm attempting to access the feed from the following URL: http://www.chinanews.com/rss/scroll-news.xml using the request module. However, the content I receive appears garbled with characters like ʷ)(й)޹. Upon inspecting the XML, I noticed that ...

What is the process for integrating a custom script prior to building in a react application?

I am facing an issue with the Chart library that I am using and in order to resolve it, I need to execute a specific script. The script can be found at this link: https://github.com/plouc/nivo/blob/master/scripts/patch-react-spring.js. I have considered ad ...

Ways to refresh UI in ReactJS without triggering a specific event

In my React application, I am displaying various pictures and GIFs that users can attach to a post. Currently, each image has an onClick handler which triggers either a modal with different options or deletes the picture if the user holds down the ctrl key ...

How do I remove the scroll bar from the datagrid using Material UI?

https://i.stack.imgur.com/lM01l.png Is there a way to remove the scroll bar at the bottom of the page? I have already attempted using autoPageSize, but it did not solve the issue. Here is the link to the autoPageSize documentation. import { DataGrid } f ...

JavaScript is unable to post content or access elements

Check out the following code: <div class="col-2"> <div class="input-group"> <label class="label">Name</label> <i ...

Issue with deploying NEXT.JS due to a failure in the build process caused by next lint

Issue I have been encountering deployment failures on Vercel due to lint errors in test files within my git repository. Despite following the recommendations from the Vercel documentation for ESLint settings, the issue persists. According to Vercel' ...

Arrange the array in chronological order based on the month and year

I'm looking for assistance with sorting an array by month and year to display on a chart in the correct order. Array1: ['Mar19','Apr18','Jun18','Jul18','May18','Jan19'....]; Desired Output: ...

Is there a way to efficiently update specific child components when receiving data from websockets, without having to update each child individually?

Currently, my frontend requires updated data every 2 seconds. The process involves the frontend sending an init message to the backend over a websocket. Upon receiving this message, the backend initiates an interval to send the required data every 2 second ...

Removing items from a todo list in JSX without relying on props or state

I am facing a challenge with utilizing a function to delete an item from an array when clicking the delete button. I am seeking a solution without relying on props or state. Could someone please point out where I may be making a mistake? The item appears ...

What is the process for setting default parameters using a recompose, lifecycle HOC?

I've created a custom recompose, lifecycle HOC: import { lifecycle } from 'recompose'; export function myHoc(title) { return lifecycle({ componentDidMount() { console.log(title) } }); } export default my ...

Finding the correct column in a drop-down menu based on a table array using AngularJS

In my controller, I have data like this: $scope.operationData = [ { "label" : "Inventory", "labelType" : "Master Tables", "type" : "PROCESSOR", "outputStreams" : 1, "elementType" : "TABLE", "name" : ...

Can someone guide me on how to personalize a marker icon in Quasar while utilizing Vue2-Leaflet for mapping?

I'm facing an issue with displaying an icon marker image in my Vue2-Leaflet and Quasar project. Instead of the desired image, I am seeing a broken image icon and encountering a 404 error in the console. Despite researching various solutions, I was abl ...