A dynamic display featuring four columns that showcase unique content every day of the week

As a beginner in coding, I am attempting to design a page with 4 columns that will showcase different titles and descriptions each day of the week.

My goal is to have a set of titles and descriptions displayed on Monday, a different set on Tuesday, and so forth for each day of the week.

Despite spending nearly a week searching online, I have been unable to determine the code required to make this daily change happen.

While I have some idea of what script to use, I'm uncertain about the exact implementation.

var today = new Date();

if (today.getDay() == 1) document.getElementById("text").innerHTML = ;
else if (today.getDay() == 2) document.getElementById("text").innerHTML = ;
else if (today.getDay() == 3) document.getElementById("text").innerHTML = ;
else if (today.getDay() == 4) document.getElementById("text").innerHTML = ;
else if (today.getDay() == 5) document.getElementById("text").innerHTML = ;
else if (today.getDay() == 6) document.getElementById("text").innerHTML = ;
else if (today.getDay() == 0) document.getElementById("text").innerHTML = ;
* {
  box-sizing: border-box;
}

body {
  color: white
}

h2 {
  color: white
}

.column {
  float: left;
  width: 15.00%;
  padding: 10px;
  margin: 1px;
}

.row:after {
  content: "";
  display: table;
  clear: both;
}
<div class="row">
      <div class="column" style="background-color:#333;">
    <h2>Titel</h2>
    <p> Description</p>
  </div>
  <div class="column" style="background-color:#333;">
    <h2>Titel</h2>
    <p> Description</p>
  </div>
  <div class="column" style="background-color:#333;">
    <h2>Titel</h2>
    <p> Description</p>
  </div>
    <div class="column" style="background-color:#333;">
        <h2>Titel</h2>
        <p> Description</p>
    </div>
</div>

If anyone can provide assistance or point me in the right direction to resolve this issue, it would be greatly appreciated. Thank you!

Answer №1

I didn't make any changes to your HTML and CSS code. Here's the JS code I added:

var data = [
    {name: "John", age: 25, city: "New York", country: "USA"},
    {name: "Emily", age: 28, city: "London", country: "UK"},
    {name: "Hiroshi", age: 30, city: "Tokyo", country: "Japan"}
];
var attributes = ["name", "age", "city", "country"];
var today = (new Date()).getDay();
var index = 0;
for (let item of document.querySelectorAll(".item")) item.innerText = data[today][attributes[index++]];

Explanation:

  • data is an array of objects containing information about different individuals
  • each object in the data array has properties like name, age, city, and country
  • attributes is an array of property names that we will use to set values later on
  • today represents the current day
  • index keeps track of which attribute we are currently setting for each item
  • document.querySelectorAll(".item")
    selects all elements with the class "item"
  • The iteration loop goes through each selected element and assigns a value based on the current day's data
  • The index variable is incremented after each assignment using index++

You can try it out here: https://jsfiddle.net/bmpw9joc/

Answer №2

When trying to retrieve an element by both class and id, it is important to note that there are differences. In reality, the class returns an array, meaning there can be multiple elements with the same class name. To access these elements, you should use getElementsByClassName instead of getElementByclass.

<script>
      var today = new Date();

      if(today.getDay() == 1) document.getElementsByClassName("text").innerHTML = ;
      else if(today.getDay() == 2) document.getElementById("text").innerHTML = ;
      else if(today.getDay() == 3) document.getElementById("text").innerHTML = ;
      else if(today.getDay() == 4) document.getElementById("text").innerHTML = ;
      else if(today.getDay() == 5) document.getElementById("text").innerHTML = ;
      else if(today.getDay() == 6) document.getElementById("text").innerHTML = ;
      else if(today.getDay() == 0) document.getElementsByClassName("text").innerHTML =      
</script>

Answer №3

Let's try this approach.

First, we will generate an array of objects, each containing display information for a specific day:

[
  {
    title: 'This is the day 0 title',
    text: 'This is day 0 text',
    description: 'This is day 0 description',
  },
  {
    title: 'This is the day 1 title',
    text: 'This is day 1 text',
    description: 'This is day 1 description',
  },
  // and so on...
]

We then retrieve the object from the array based on the index representing the current day:

// determine the day of the week (0 for Sunday, 6 for Saturday)
const dayIndex = date.getDay();

// fetch the data for this day from the array
const info = contentsByDay[dayIndex];

The variable info now holds the object for that particular day, for example:

{
  title: 'This is the day 1 title',
  text: 'This is day 1 text',
  description: 'This is day 1 description',
}

We proceed to iterate over the properties of the object using a for...of loop.

for (const prop in info) {
  // executed for each property ('title', 'text', 'description')
}

Within the loop, we search for a DOM element (like a div) with a class corresponding to the property name:

// similar to elem.querySelector('.title') when prop === 'title'
const div = elem.querySelector(`.${prop}`);

If we locate the element (div), we update its innerHTML with the value from the object:

if (div) {
  // info[prop] represents info.title for prop === 'title'
  div.innerHTML = info[prop];
}

Finally, apply some CSS rules to arrange them horizontally:

.day {
  display: flex;
}

.day > * {
  /* dividing space equally among 3 fields */
  flex: 1 1 33.3%;
}

// To simplify, quickly create an array with objects for each day.
// Each entry in the array has title, text, and description fields.
const contentsByDay = Array.from({length: 7}, (_, i) => ({
  title: `This is the day ${i} title`,
  text: `This is day ${i} text`,
  description: `This is day ${i} description`,
}));

// function to update the DOM with information for a given date.
// Defaults to today if no date provided.
function showDayInfo(date = new Date()) {
  const dayIndex = date.getDay(); 
  const info = contentsByDay[dayIndex]; 
  const elem = document.querySelector('.day'); 
  for (const prop in info) { 
    const div = elem.querySelector(`.${prop}`); 
    if (div) { 
      div.innerHTML = info[prop]; 
    } 
  }
}

showDayInfo();
.day {
  display: flex;
}

.day > * {
  flex: 1 1 33.3%;
}
<div class="day">
  <div class="title"></div>
  <div class="text"></div>
  <div class="description"></div>
</div>

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

Calculate the total sum of input values using jQuery

Here is the HTML I've been working with: I am trying to create a script where one textbox will display the total amount, and another textbox will display the following data: "name": [{ "id": 3, "qty": 2 }, { "id": 4, "qty": 5 }] Here's ...

How can I use a Google extension to interact with buttons on a webpage?

In my project, I have created an extension file named github.js jQuery(document).ready(function($) { console.log('github.js'); // btn btn-primary shelf-cta var button = $('.btn.btn-primary.shelf-cta'); console.log('button. ...

Guide to preserving a .docx document in react js

My current project involves a firebase function that is responsible for creating a word document from a template and sending it back to the client. The issue I am facing is that although the buffer containing the data is being sent correctly to the client, ...

'addEventListener' and 'onclick' functions are restricted to the 'window' element and cannot be used on any other element, such as a button

I am currently working on developing a Snakes and Ladders board game using JavaScript. I have encountered an issue with adding 'onclick' or 'addEventListener' events to the buttons in the game. When I try to attach these events to the b ...

Navigation bar subtitle with items aligned to the right

My navigation bar includes a subtitle, and I implemented the technique found here to add it. However, after adding the subtitle, my nav bar lost its right alignment. Some items in the nav bar need to be aligned to the right, but they are no longer since I ...

Adding a clear field icon to an input field: Step-by-step guide

When using AngularJS 1.3, a standard input field with type="date" comes with a convenient "Clear field" icon as shown here. Is there a method to incorporate this same "Clear field" icon into an input field with type="text"? ...

`Changing the iframe content dynamically with next and previous buttons: a step-by-step guide`

function displayPDF(fileSlNo){ var data = { pageMode: "PDF_DISPLAY", fileSlno: fileSlNo }; var d = $.param(data); var request = $ .ajax({ type: "GET", url:"folderNavigation.do?"+d, dataType : "TEXT", success: functio ...

Toggle textboxes using jQuery depending on the radio button choice

I'm trying to make specific textboxes appear when a particular radio button is clicked on my form, but I want them to remain hidden otherwise. Here's an example of what I've implemented: HTML: Radio buttons: <p>Show textboxes<inpu ...

How can you modify the HTML tags before Bootstrap overrides them?

Imagine having a code snippet like this: <style> #container ul li{ font-size:50px;} .myclass1 ul li{ font-size: 20px;} </style> <div id="container"> <ul> <li> <div class="myclass1"> ...

What is the best way to display an HTML array?

I'm currently facing an issue with rendering an array containing both <p> and <div> items as HTML. Despite my attempts to render them properly, the values appear as plain code instead of formatted paragraphs. To illustrate, let's cons ...

Stream of information that triggers a specific action based on a specified condition

I'm dealing with an observable stream where I need to make two calls after retrieving the initial object using two id's found within the object. One of these id's, siteId, is optional and may or may not be present. If it is present, I need t ...

What is the best approach to managing this scenario where the document is ready?

Just a quick question. I have several JavaScript functions written in this format: var app={ start:function(){ //do something and call calculate }, //end start calculate:function(){ //do more stuff } //end calculate }; //en ...

Is it possible to deinitialize data tables (remove from memory)?

I'm currently utilizing data-tables (with jQuery) on my website. The particular data-table I have implemented seems to be consuming excessive memory in javascript, causing a slowdown in other functionalities. Is there a way for me to de-initialize th ...

Limiting the input in a text box to only allow whole numbers and no decimal values

What is the best way to limit a textbox to only accept whole numbers and exclude decimal values and alphabets? ...

The domain retrieval is contingent on the language preference of the user

A task has been assigned to create a script in JavaScript/jQuery (or other suitable technologies) that will return a domain with a .pl extension if the user's browser language is set to Polish. Otherwise, the script should return a .eu domain extensio ...

Querying jQuery: How to Retrieve the ID of a Link

I have a set of links, each with their own unique id: <li><a id="about" href="#">About</a></li> <li><a id="call-us" href="#">Contact us</a></li> <li><a id="home" href="#">Head on home</a>&l ...

What is the best way to enforce a left alignment for a menu?

I am looking to align the titles on the left side. I suspect that the issue lies in this particular line of code. Can someone help me identify which properties I should adjust to resolve this problem? https://i.sstatic.net/XWCsd.png Interestingly, the ic ...

The Facebook Comments feature on my React/Node.js app is only visible after the page is refreshed

I am struggling with getting the Facebook Comment widget to display in real-time on my React application. Currently, it only shows up when the page is refreshed, which is not ideal for user engagement. Is there a way to make it work through server-side r ...

How to modify a Python script to print in a specific div element instead of the Chrome console?

Currently conducting preliminary tests on executing a Python script within a Chrome extension. The code provided below is functional, but I am seeking assistance on how to display the value in a div element instead of logging it to the console. Unfortunate ...

How can you tap into local storage in CSS while utilizing a chrome extension?

Can I access local storage from a Chrome extension's options file using CSS? Is it possible to use JavaScript to define a variable that can be utilized in CSS, or is local storage only accessible through JavaScript? If local storage is restricted to J ...