Script to alter div style based on the day of the week

Check out my project: http://jsfiddle.net/yL0o1cy0/

.calendar {
  width: 850px;
  height: 500px;
  background-color: #141414;
  border-radius: 10px;
  padding-top: 10px;
  margin-top: 15px;
  margin-left: 15px;
}
#calendartest1 {
  width: 778px;
  height: 200px;
  position: relative;
  margin-left: auto;
  margin-right: auto;
}
#calendartest2 {
  width: 778px;
  height: 200px;
  position: relative;
  margin-left: auto;
  margin-right: auto;
  margin-top: 50px;
}
#calendartest1 h2 {
  color: #999999;
  text-align: center;
  margin-top: 0px;
  margin-bottom: 0px;
}
#calendartest2 h2 {
  color: #999999;
  text-align: center;
  margin-top: 0px;
  margin-bottom: 0px;
}
.day {
  width: 110px;
  float: left;
  border-left: 1px solid #404040;
}
.dayname {
  text-align: center;
  background-color: #49CEFF;
  height: 30px;
  border-radius: 0px 5px 0px 5px;
  margin-left: 3px;
  margin-right: 3px;
  margin-top: -15px;
}
.dayname p {
  padding-top: 5px;
  color: white;
  font-weight: bold;
  text-shadow: 0px 0px 10px black;
}
.daycontent {
  text-align: center;
  margin-top: 5px;
  height: 160px;
}
.daycontent a:link,
a:visited {
  display: block;
  margin-left: 2px;
  margin-right: 2px;
  margin-top: 2px;
  padding-top: 2px;
  padding-bottom: 2px;
  color: white;
  text-decoration: none;
  font-size: 12px;
}
.daycontent a:hover,
a:active {
  background-color: black;
  color: #49ceff;
}
<div class="calendar">
  <div id="calendartest1">
    <h2>Test1</h2>
    <div class="day">
      <div class="dayname">
        <p>Monday</p>
      </div>
      <div class="daycontent">
        <a href="">test</a>
        <a href="">test</a>
        <a href="">test</a>
      </div>
    </div>
    // more days...
  </div>
  <div id="calendartest2">
    <h2>Test2</h2>
    <div class="day">
      <div class="dayname">
        <p>Monday</p>
      </div>
      <div class="daycontent">
        <a href="">test</a>
        <a href="">test</a>
        <a href="">test</a>
      </div>
    </div>
    // more days...
  </div>
</div>

I'm looking to dynamically change the background color of each day's box in my calendar. For example, on Monday I want the background to change from #49CEFF; to #242424;, and likewise for other days. Any suggestions on how to achieve this?

Answer №1

Here is one method to achieve this:

function highlightToday(color) {

    var dayElements = Array.prototype.slice.call(document.querySelectorAll('div.dayname p'), 0),
        daysOfWeek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
        currentDayIndex = new Date().getDay();

    dayElements.forEach(function (dayElement) {
    
        if (dayElement.textContent.trim() === daysOfWeek[currentDayIndex]) {
            dayElement.parentNode.style.backgroundColor = color;
        }
    });
}

highlightToday('#242424');

If you prefer, instead of setting the background-color directly in JavaScript, you can add a class name 'today' to the parent element:

function highlightToday(color) {
    var dayElements = Array.prototype.slice.call(document.querySelectorAll('div.dayname p'), 0),
        daysOfWeek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
        currentDayIndex = new Date().getDay();

    dayContainers.forEach(function(dayElement) {
        if (dayElement.textContent.trim() === days[dayIndex]) {
            dayElement.parentNode.classList.add('today');
        }
    });
}

highlightToday();

Answer №2

To accomplish this task, simply insert some JavaScript code along with a CSS class.

Check out the updated JSFiddle

The freshly designed CSS class

.current-day {
    background-color: #242424 !important;
}

The JavaScript logic - Determine the current day of the week and then identify all <p> elements that contain the name of today's weekday to apply the new CSS style.

var now = new Date();
var daysOfWeek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

var today = daysOfWeek[now.getDay()];

var paragraphs = document.getElementsByTagName('p');

for (var idx = 0; idx < paragraphs.length; idx++) {
     if (paragraphs[idx].innerText.indexOf(today) !== -1) {
         paragraphs[idx].parentNode.className += " current-day";
     }
}

Answer №3

To determine the current day, you can consistently check the time either every minute, 10 seconds, or even every second (view fiddle). Processing one operation per second is simple and using new Date() won't impact performance significantly.

HTML Structure:

<div class="day">Monday</div>
<div class="day">Tuesday</div>
<div class="day">Wednesday</div>
<div class="day">Thursday</div>
<div class="day">Friday</div>
<div class="day">Saturday</div>
<div class="day">Sunday</div>
<div id="time"></div>

CSS Style:

.day {
    padding: 10px 50px;
    font-size: 20px;
    background: #ccc;
    margin: 0 0 10px 0;
}

.current {
    background: #09c; /*Applied to current day via JS*/
}

Javascript Functionality:

window.onload = function() { //ensure DOM is loaded
    var weekHeadings = document.getElementsByClassName('day'); //calendar days array
    var currentTime = document.getElementById('time');
    var now = null;

    var setCurrentDay = function(elements, currentIndex) {
        var current = document.getElementsByClassName('current');
        if (current.length > 0)
            current[0].className = 'day';
        
        if (currentIndex < 0)
            elements[6].className = 'day current';
        else
            elements[currentIndex].className = 'day current';
    };

    var updateTime = setInterval(function() {
        var now = new Date();
        var hours = now.getHours();
        var minutes = now.getMinutes();
        var seconds = now.getSeconds();

        setCurrentDay(weekHeadings, now.getDay() - 1);
        currentTime.innerHTML = hours +':'+ minutes +':'+ seconds;
    }, 1000);
};

The code includes comments and references for easier understanding in the fiddle along with a timer to track updates.

If the day changes, the date object will reflect it automatically. The function runs every second even after page refresh, ensuring accurate timekeeping.

Answer №4

To identify the current day of the week and adjust the background color, you'll need to utilize Javascript.

getDay()

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

Having difficulty retrieving objects within a foreach loop of object keys that do not meet the criteria of the string.prototype.replace method

Currently, I am working on looping over objects within a key:value array in JavaScript to use the string.prototype.replace method for paths to JS files in GulpJS concat tasks. The objective is to generate a list of paths that GULP can utilize, but they re ...

Default cross-origin behavior of the Fetch API

According to the Fetch Specifications, the default Fetch mode is 'no-cors'. The specifications state that a request's mode can be "same-origin", "cors", "no-cors", "navigate", or "websocket". Unless otherwise specified, it defaults to "no ...

Using Selenium to choose a dropdown menu option - the dropdown menu will only appear once a search query has been entered into the

Seeking assistance with choosing a pop-up dropdown menu option using selenium in Python within Google Colab. You can find the URL here: This website allows searching by geography. Once you enter a term in the Domain field (I'm using 'Cerrado&ap ...

Navigating through React Native - A guide to accessing the initial navigation state on React Navigation

Is it possible to retrieve the initial state in a similar format as what is provided by the onStateChange prop in NavigationContainer? Unfortunately, onStateChange does not run during the initial render. While I was successful in obtaining the state whil ...

Expanding CSS Grid to Occupy Remaining Area

I'm currently utilizing CSS grid to construct a basic 3 column layout. Here's a snippet of my code... .container { display:grid; grid-template-columns:1fr 1fr 1fr; } ...

Implementing text overlays on images within a Bootstrap 4 navigation bar

I am struggling to grasp the flex structure in Bootstrap. I'm attempting to overlay text on an image within the navbar, but it seems the container of the navbar is causing issues. Perhaps my containers are not set up correctly. Any assistance would be ...

What is the method for determining the overall page load time of a website, taking into account the total loading time instead of just the document.ready()

I recently attempted to create a function using either JavaScript or Python with Selenium to measure the page load time of a website. While document.ready() gives me the DOM load time, it may not capture AJAX calls that occur afterwards. I noticed there i ...

Revamping the login interface for enhanced user

Whenever I attempt to login by clicking the login button, there seems to be an issue as it does not redirect me to any other page. Instead, I am left on the same page where I initially clicked the button. The intended behavior is for users to be redirected ...

Is there a way to efficiently update multiple rows at once in MySQL using an array in Node.js?

I am attempting to use the UPDATE function to modify three different columns in my table named "stores." Specifically, I want to add "openingTime," "closingTime," and "phoneNumber" values and associate them with a storeId that already exists in the table. ...

Having trouble aligning my fixed div to the center of the screen

I have scoured numerous resources in search of a solution to my problem, but nothing seems to work for me. I have created a simple portfolio site where I want the word 'Developer' to be the first thing visible upon loading, followed by the portfo ...

I am looking to insert the indexes of an array into a table data cell (<td>), with the select options being the array's indexes

I'm looking for a way to add the indexes of an array as options in a select field. However, the code provided below is not working as expected. <?php $str4 = "select * from fee_names where status = '1' "; $res4 = mysql_quer ...

Incorporating one-of-a-kind images into your JavaScript objects

Big shoutout to dmikester1 for sharing a LeaderBoard code that leverages Javascript data to organize players by their points. The current implementation involves using the same image for each player's profile, but I have a vision to customize the pic ...

Retrieve the previous URL for redirection purposes

I have a specific route set up in my application. If the user is not logged in, they are redirected to the login page. I am currently working on capturing the previous route that the user came from so that I can redirect them back there after they have suc ...

The HTML code is failing to load the font

I'm having trouble with the font on my website not loading properly. I added the Abel font family to my code, but it doesn't seem to be working. Here is a snippet of what I have tried: <p style="margin-left: 620px; margin-top: -355px;" ...

Effortlessly alter the appearance of Stripe Elements using Next-themes for dynamic style changes

I've been working with Stripe Elements and implementing dynamic changes to input styles based on the theme. Everything is functioning as intended, but I'm running into an issue when switching themes while on the page containing the Stripe Element ...

How can the CORS issue be resolved when sending a form from a client to an AWS API gateway function?

Within my front end React application, I am looking to implement a contact form that will submit data to a Lambda function via an API Gateway with a custom domain attached. The frontend operates on the domain dev.example.com:3000, while the API Gateway is ...

Directives causing disruption to one another

Two directives are at the same level in my code: function signUpForm(djangoAuth, Validate){ return{ restrict:'A', controller:["$rootScope","$scope",function($rootScope, $scope){ $scope.submitFunction = function(formData){ ...

What is the syntax for accessing a dictionary item within a <span> tag using JavaScript?

I'm working on a new functionality for a website that involves using a dictionary to store information about clubs, events, and times. var clubName = {}; var event = {}; var time = {}; var dict = new Map(); dict.set(clubName, "G ...

Struggling with a malfunctioning ComponentDidMount function that devoured 95,000 of my daily calls in React

I've encountered an issue with my app development process. I am currently working on a simple app that utilizes the FourSquare API. Users input a location and receive venue information through this.state.places. I successfully looped through the da ...

Rendering basic JSON data from the console to an HTML page using Angular

I have been utilizing openhab for sensor monitoring. To extract/inject the items(things), sensor properties, and room configuration through a web interface, I am making use of openhab's REST queries which can be found here - REST Docs. Wanting to cre ...