Is it possible to modify text periodically throughout the day using JavaScript?

I'm new to JavaScript and looking for a way to create a schedule on my website. The schedule changes every half hour with different speakers, and I want to display the speaker's name based on the time slot.

Currently, I have a working solution but it involves hard-coding 48 if statements for each top and bottom of the hour - not the most efficient approach. Here is the code:

<html>
<body>
<h1>Test JavaScript</h1;
<p id="demo"></p>
<script>
setInterval(getSchedule, 1000);
function getSchedule(){
var today = new Date()
var curHr = today.getHours()
var curMin = today.getMinutes()
if (curHr == 1 && curMin < 30) {
document.getElementById("demo").innerHTML = "John";
} 
else if (curHr == 1 && curMi...

I'd like to find a way to simplify this code. Possibly using an array containing all speaker names, but I'm unsure how to iterate through it at specific times. Any suggestions would be appreciated. Thanks!

Answer №1

Instead of using multiple if statements, you can simplify the code with:

  var timeDisplay = currentHour + (currentMinute < 30 ? ":00" : ":30");
   document.getElementById("time").innerHTML = timeDisplay;

Now, update your function to look like this:

function showTime(){
      var now = new Date();
      var currentHour = now.getHours();
      var currentMinute = now.getMinutes();
      var timeDisplay = currentHour + (currentMinute < 30 ? ":00" : ":30");
   document.getElementById("time").innerHTML = timeDisplay;
}

Answer №2

Do you understand what needs to be accomplished?

<html>
<body>

<h1>Testing Java Script</h1>

<p id="output"></p>

<script>
setInterval(getSchedule, 1000);

var speakers = { "10:00": "kenvin", "10:30": "faker" };

function getSchedule(){
var currentDate = new Date()
var currentHour = currentDate.getHours()
var currentMinute = currentDate.getMinutes()

console.log([currentHour, (currentMinute >= 30) ? "30" : "00"].join(":"));
var keyValue = [currentHour, (currentMinute >= 30) ? "30" : "00"].join(":");

document.getElementById("output").innerHTML = keyValue + " - " + speakers[keyValue];
}
</script>
</body>
</html>

Answer №3

All you need is a single IF statement...

if (currentMinutes < 30) { displayTime.innerHTML = currentHour+':00';} else { displayTime.innerHTML = currentHour+':30';}

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

Retrieve a form (for verification purposes) from a separate AngularJS component

I'm facing an issue with accessing a form from one component to another in my project. One component contains a form, and the other has navigation buttons that, when clicked, should validate the form before moving on to the next step. However, I alway ...

The AJAX load event listener triggers prior to receiving a response from the server

When working on a script to upload images via AJAX, the process is as follows: a user selects an image using a form file input field. The form contains an onsubmit function that prevents the page from reloading after submission. Within this function, data ...

Receiving data through multiple ajax calls nested within another ajax call

Hello everyone, I am diving into the world of AJAX/jQuery and would appreciate your patience as I try to navigate through it. I have an interesting challenge ahead so let's see how we can tackle it together ...

Limitations of jQuery: onClick function not transferable

I am struggling to achieve the following functionality for my navbar dropdown menus: When the screen size is greater than 992px, I want the navbar dropdowns to open on mouse enter. For screens smaller than 992px, I want the dropdowns to open on ...

Reset the event to its default action in jQuery following the use of event.preventDefault()

I found a solution on Stack Overflow to disable the arrow, pgdown, and pgup keys from scrolling using jQuery. However, I now need to revert these keys back to their default actions after calling event.preventDefault() in my code. Can someone help me achie ...

There seems to be a glitch preventing Highchart from functioning within a jQuery function

Hello there! I'm currently utilizing the highchart API to generate graphs in a loop. for(i=1;i<10;i++) { xseries = "{'INCOPAV','B&M','SGS-ETSA'}"; yseries = "[{name: &apos ...

How to display an unordered list horizontally in HTML

I'm working on a screen that has filters displayed vertically, but I want to align them horizontally and have the filter options arranged in two columns. I've tried using CSS properties like spacing, clear, and display block, but the checkboxes/l ...

"How can you enhance the performance of JavaScript and CSS in a Chrome Extension without using exclude_matches/globs or excluding domains

I have been in the process of creating a Chrome Extension, and unfortunately, when I tried to make it work on specific URLs, I encountered an issue. While Chrome has options like exclude_matches and exclude_globs for this purpose, there seems to be a bug i ...

Ensuring the accuracy of forms using third-party verification services

While working on an Angular form validation using an external service, I encountered a cannot read property of undefined error. The component contains a simple form setup: this.myForm = this.fb.group({ username: ['', [this.validator.username] ...

Issue with conditional image source URL in NUXT component not functioning as expected

I am currently attempting to dynamically render an image source path based on the provided prop in the component. In case the image does not exist in the assets folder, I want to include a fallback path. Below is the code snippet for my image tag: <img ...

Can an uploaded video file have frames and audio stripped using JS since iPhone doesn't allow inline video playback?

Summary Can JavaScript be used to extract frames and audio data from an uploaded video for streaming to a custom canvas or audio player? What are the possibilities and limitations of this approach? While I have not personally attempted to manipulate raw ...

Obtain the appropriate selection in the dropdown based on the model in Angular

I am working on a dropdown menu that contains numbers ranging from 1 to 10. Below is the HTML code for it: <div class="form-group"> <label>{{l("RoomNumber")}}</label> <p-dropdown [disab ...

Verify authentication on a SignalR console application using a JavaScript client

Here is the scenario and solution I am currently working on: In project one, I have a SignalR console application that handles the logic, including authentication using Entity Framework to query the database. In project two, I have an ASP.Net web applicat ...

Leveraging AJAX Post Data in NodeJS using Express

I'm currently working on retrieving the values I send for an ajax post within my node application. After referring to a helpful post on Stack Overflow, here is what I have implemented so far: Within Node.js: var express = require('express&apos ...

Troubleshooting Tips for Fixing the "ER_HOST_IS_BLOCKED: Host 'abc' has been blocked due to numerous connection errors" Issue

After conducting a speedy search on Google, I found numerous solutions to rectify this issue. However, it seems none of them offer advice on getting to the bottom of the problem. It appears that the error occurs whenever my application hits a limit on co ...

CSS - Help! Seeing different results on Internet Explorer

I'm currently handling an OSCommerce website, and I'm trying to figure out why this issue is occurring. You can view the website at this link: The layout looks completely different on Internet Explorer, and I'm puzzled as everything should ...

Activate only the content of the parent div in a duplicated list using Javascript

Exploring the world of JavaScript, I am focusing on mastering event listeners and node lists. However, I have hit a roadblock when it comes to the JavaScript syntax for a specific query. My goal is to extract the innerHTML of each button and display it in ...

npm build issues stemming from browserlist configurations

I am encountering an issue with my create-react-app failing to build, showing the following error: ./src/index.css Module build failed: BrowserslistError: Unknown browser query `dead` at Array.forEach (<anonymous>) I have carefully reviewed my ...

Restricting the Vue for-loop results to display only the current item in use

Currently, I am utilizing a for-loop to retrieve all of my posts, followed by employing a partial to obtain a list of all the usersThatUpvoted on that post. <div v-for="p in posts" style="padding: 16px"> <div> &l ...

invoke a function through a form in Angular

I am encountering an issue with invoking a function from Angular. This particular function has a dual purpose - it uploads an image to S3 and saves the form data along with the URL of the image in the MongoDB database. Below is the HTML snippet where I cal ...